In C# how can I deserialize this json when one field might be a string or an array of strings?

纵然是瞬间 提交于 2019-12-01 06:15:50
Yahia

try

  var contacts = (new JavaScriptSerializer().DeserializeObject(theAboveJsonString) as Dictionary<string, object>)["contacts"];

  if (contacts is object[])
  {
      jobInfo.contacts = String.Join("; ", contacts as object[]);
  }
  else
  {
      jobInfo.contacts = contacts.ToString(); 
  }

For reference see MSDN and here.

yamen

You may be interested in some details here: JSON.net - field is either string or List<string>

If you're willing to use Json.NET, have this function:

public string[] getAsArray(JToken token)
{
    if (token.HasValues)
    {
        return token.Select(m => string(m)).ToArray();
    }
    else
    {
        return ((string)token).Split(",").Select(s => s.Trim()).ToArray();
    }
}

Then usage:

var json = "...";
JObject o = JObject.Parse(json);
string[] contacts = getAsArray(o["contacts"]);

For either JSON the result should be the same.

Try to deserialize contacts into a string array instead of a plain string:

string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;

if the JSON variable is holding a plain string, use:

string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts.Split(',');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!