Conditionally deserialize JSON string or array property to C# object using JSON.NET? [duplicate]

寵の児 提交于 2019-12-07 15:24:34

问题


I have a defined C# object based off a very complex JSON I'm getting from a third party API. Here's a piece of it:

{"alarmSummary":"NONE"}

The corresponding property in C# would be:

public string alarmSummary {get; set;}

And I would get this converted by using my typical JSONConvert from JSON.NET:

var alarms = JSONConvert.DeserializeObject<MyClass>(jsonString); 

However, the API will put alarms in this format, as an array, and "NONE" when there aren't any as a string:

{"alarmSummary" : ["AHHH Something went wrong!!", "I'm on fire!!"]}

Which means in C# it would need to be:

public string[] alarmSummary {get; set;}

If I could, I would just have the JSONConvert deserialize the "NONE" string into an array of just one entry. Is there a way to set conditions on this property, or will I have to take the whole complex JSON string and hand convert it?


回答1:


This one should be easy - you can set your alarmSummary as object and then have separate property that evaluates alarmSummary and returns null or array depending on the value.

    public object alarmSummary { get; set; }

    protected string[] alarmSummaryCasted
    {
        get
        {
            if (alarmSummary is String)
                return null;
            else
                return (string[]) alarmSummary;
        }
    }



回答2:


If you are expecting only those two combinations, you could make use of the dynamic keyword and check deserialized object:

string json = "{\"alarmSummary\":\"NONE\"}";
//string json = "{\"alarmSummary\" : [\"AHHH Something went wrong!!\", \"I'm on fire!!\"]}";

string[] alarmSummary;
dynamic obj = JsonConvert.DeserializeObject(json);
if (obj.alarmSummary.Type == JTokenType.Array)
   alarmSummary = obj.alarmSummary.ToObject<string[]>();
else
   alarmSummary = new[] { (string)obj.alarmSummary.ToObject<string>() };


来源:https://stackoverflow.com/questions/35782400/conditionally-deserialize-json-string-or-array-property-to-c-sharp-object-using

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