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 the JSON data below into a class / object

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

My idea is that ShippingMethodin JSON it is an object, but I just want to go to ShippingMethod.Code(in JSON), which will go in ShippingMethodas stringin a Orderclass during deserialization.

how can I achieve this goal by using Json.NET ?

I believe that I can use it using CustomJsonConverter . But I am embarrassed. The example in the docs is for WriteJson, but not for ReadJson.

+11
source share
3 answers

JsonConverter . :

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;
    }
}
+15
 dynamic o = JsonConvert.DeserializeObject(json);
 var order = new Order
 {
     Id = o.Id,
     ShippingMethod = o.ShippingMethod.Code
 };

, " Order

+6

JsonProperty JsonIgnore, ... , :

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);
+4

Source: https://habr.com/ru/post/1659926/


All Articles