Home > Back-end >  Deserializejson to pojo where json field has different data types C#
Deserializejson to pojo where json field has different data types C#

Time:05-18

I know there are multiple thread answering this issue but my issue is little different Below are the classes and json I am using. How to handle the deserialization of same property with different data types object and double values. This is what I tried- 2 sample of JSON :

1)First json takes value as double type-

{
  "$type": "SomeType",
  "Mode": "Detailing",
  "form": {
    "value": 0.1
    }
}

2)Second json takes form type value-

 {
    "$type": "SomeType",
    "Mode": "Detailing",
    "form": {
        "value": {
            "day": 1,
            "month": 5,
            "year": 2025
        }
}

POJO clases I have create a root class as follow-

public class Root{
       [JsonProperty("type")]
        public string type{ get; set; }
        [JsonProperty("mode")]
        public String mode{ get; set; }
        [JsonProperty("form")]
        public Form form{ get; set; }
}

the form class as following-

public class Form{
        [JsonProperty("value")]
        private Value myValue { get; set; }

}
public class Value
    {
        [JsonProperty("day")]
        private int day { get; set; }
        [JsonProperty("month")]
        private int month { get; set; }
        [JsonProperty("year")]
        private int year { get; set; }
}

I am using JsonConverter for deserialize the value in json object

public class Resolver : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(Root).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject item = JObject.Load(reader);
            if (item["form"]["value"].Type == JTokenType.Float)
            {
               //how to handle double type?
            }
            else if (item["form"]["value"].Type == JTokenType.Object)
            {
                return item.ToObject<Root>();
            }
           
        }

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

CodePudding user response:

you can use this Form class instead of custom json converter

var data = JsonConvert.DeserializeObject<Data>(json);

public class Form
{
    [JsonIgnore]
    public double myValueDouble { get; set; }
    [JsonIgnore]
    public Value myValue { get; set; }
    [JsonConstructor]
    public Form(JToken value)
    {
        if (value is JValue) myValueDouble =  value.ToObject<double>();
        else myValue=(Value) value.ToObject<Value>();
    }
    public Form()
    {

    }
}
  • Related