0

I'm trying to serialize my realm object to a json string, but I'm getting Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'Id' on 'Goodbuy.Models.product'.' Here is the method where the serialization happens:

    async void OnItemSelected(product item)
    {
        if (item == null)
            return;

        var model = await ProductService.GetProduct(item.Id);
     
        //Convert Object to string 
        string jsonStrObj = await Task.Run(() => JsonConvert.SerializeObject(model));

        // This will push the ItemDetailPage onto the navigation stack
        
        await Shell.Current.GoToAsync($"{nameof(ItemDetailPage)}?ProductModel={jsonStrObj}");


    }

below is my realm object class:

public class product :RealmObject
{
    [PrimaryKey]
    [MapTo("_id")]
    public ObjectId? Id { get; set; }
    [MapTo("brand")]
    public string Brand { get; set; }
   
    [MapTo("image_url")]
    public string ImageUrl { get; set; }
    [MapTo("name")]
    public string Name { get; set; }
   
    
}

1 Answers1

1

Using the JsonObject attribute with MemberSerialization.OptIn argument, and creating custom converter that just spits out the Guid portion of the ObjectId Json.NET how to serialize an ObjectId.

 [JsonObject(MemberSerialization.OptIn)]
public class product : RealmObject
{
    [PrimaryKey]
   
    [JsonProperty(PropertyName = "id")]
    [JsonConverter(typeof(ObjectIdConverter))]
    public ObjectId? Id { get; set; }
  
    [JsonProperty(PropertyName = "brand")]
    public string Brand { get; set; }

   
    [JsonProperty(PropertyName = "image_url")]
    public string ImageUrl { get; set; }
    
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }


}

 [JsonObject(MemberSerialization.OptIn)]
public class product : RealmObject
{
    [PrimaryKey]
   
    [JsonProperty(PropertyName = "id")]
    [JsonConverter(typeof(ObjectIdConverter))]
    public ObjectId? Id { get; set; }
  
    [JsonProperty(PropertyName = "brand")]
    public string Brand { get; set; }

   
    [JsonProperty(PropertyName = "image_url")]
    public string ImageUrl { get; set; }
    
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }


}
Cherry Bu - MSFT
  • 10,160
  • 1
  • 10
  • 16