What is the best practice to deserialize a JSON object with field that might be either string or int?

强颜欢笑 提交于 2019-12-10 18:24:05

问题


I am trying to use Newton Json Deserializer to deserialize json object which looks like this:

{
  "grades": 97
}

Or this:

{
  "grades": ""
}

I wonder how should I properly define a DTO class in C# to represent the this object? Thanks!


回答1:


Please try with dynamic keyword:

public class Rootobject
{
     public dynamic grades { get; set; }
}

It will work with both string and int. For more info refer to using dynamic type.

UPDATE:

Then to convert into int or string I will use Convert.ToString() because it handles null values and for int I will use Int32.TryParse() because I can better control conversion to int if input drades are not properly formatted.

UPDATE:

Any nullable type in C# will become null if grades are "". For that purpose, you can use int?. But if grades are something like "3ds" then you have to use some dynamic approach.




回答2:


I would rather use a custom JsonConverter on your POCO, which would ensure that the object gets deserialized into one expected type, rather than using object or dynamic, and then having to treat that property with suspicion throughout your codebase.

Here's how I would do it:

public class IntConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value.GetType() == typeof(int))
            writer.WriteValue((int)value);
        else
            writer.WriteValue(value.ToString());
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => 
        ParseInt(reader.Value.ToString());

    public override bool CanConvert(Type objectType) =>
        objectType == typeof(int) || objectType == typeof(string);

    private static int ParseInt(string value)
    {
        int parsedInt = 0;
        int.TryParse(value, out parsedInt);
        return parsedInt;
    }
}

And then use this JsonConverter in your POCO like this:

public class Student
{
    [JsonProperty("grades"), 
    JsonConverter(typeof(IntConverter))]
    public int Grades;
}

I would find this is 'best practice' for these things.



来源:https://stackoverflow.com/questions/42307269/what-is-the-best-practice-to-deserialize-a-json-object-with-field-that-might-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!