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

后端 未结 3 1256
南方客
南方客 2021-01-14 04:05

I have an asp.net-mvc website and i am reading in Json string from a Database. Here is the following json in a DB. It could look like this:

{\"description\"         


        
相关标签:
3条回答
  • 2021-01-14 04:22

    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.

    0 讨论(0)
  • 2021-01-14 04:28

    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(',');
    
    0 讨论(0)
  • 2021-01-14 04:31

    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.

    0 讨论(0)
提交回复
热议问题