Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Deserialization using Json.NET

I have a class

public class Order
{
   public int Id { get; set; }
   public string ShippingMethod { get; set; }
}

and I want to deserialize a JSON data below into the above class/object

string json = @"{
  'Id': 1,
  'ShippingMethod': {
     'Code': 'external_DHLExpressWorldwide',
     'Description': 'DHL ILS Express Worldwide'
  }
}";

My idea is that ShippingMethod in JSON is a object, but I just want to get to ShippingMethod.Code (in JSON) that will pass into ShippingMethod as string in Order class during deserialization.

how can I accomplish that goal using Json.NET?

I believe I can accomlish it using CustomJsonConverter. But I get confused. The example in the docs just for WriteJson, but not ReadJson.

like image 688
Habibillah Avatar asked Nov 05 '16 14:11

Habibillah


People also ask

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How do I create a custom JSON deserializer?

The @JsonDeserialize annotation is used to declare custom deserializer while deserializing JSON to Java object. We can implement a custom deserializer by extending the StdDeserializer class with a generic type Employee and need to override the deserialize() method of StdDeserializer class.

How does JSON deserialization work?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.


3 Answers

I just resolve my problem using JsonConverter as I mentioned above in my question. Below my complete code:

public class Order
{
    public int Id { get; set; }

    [JsonConverter(typeof(ShippingMethodConverter))]
    public string ShippingMethod { get; set; }
}

public class ShippingMethodConverter : JsonConverter
{

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException("Not implemented yet");
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return string.Empty;
        } 
        else if (reader.TokenType == JsonToken.String)
        {
            return serializer.Deserialize(reader, objectType);
        }
        else
        {
            JObject obj = JObject.Load(reader);
            if (obj["Code"] != null) 
                return obj["Code"].ToString();
            else 
                return serializer.Deserialize(reader, objectType);
        }
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return false;
    }
}
like image 186
Habibillah Avatar answered Oct 16 '22 16:10

Habibillah


 dynamic o = JsonConvert.DeserializeObject(json);
 var order = new Order
 {
     Id = o.Id,
     ShippingMethod = o.ShippingMethod.Code
 };

Deserialize the object as dynamic and then fill the Order object by accessing to the dynamic object properties

like image 33
Tinwor Avatar answered Oct 16 '22 18:10

Tinwor


You can use JsonProperty and JsonIgnore attributes to direct the deserialization process... So your model can be:

public class Order
{
    public int Id { get; set; }

    [JsonIgnore]
    public string ShippingMethod
    {
        get
        {
            return (string)TempShippingMethod?["Code"];
        }
    }

    [JsonProperty("ShippingMethod")]
    private JObject TempShippingMethod { set; get; }
}

var res = JsonConvert.DeserializeObject<Order>(json);
like image 12
L.B Avatar answered Oct 16 '22 18:10

L.B