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

≯℡__Kan透↙ 提交于 2019-12-06 01:43:20

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;
        }
    }

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