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

c#, deserialization, javascriptserializer, json

Solution

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.

Problem

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": "Test", "contacts": ["joe@gmail.com", "bill@yahoo.com"], "enabled": true} ``` or this: ``` {"description": "Test", "contacts": "joe@gmail.com, bill@yahoo.com", "enabled": true} ``` so as you can see, the contacts field is either: - a string (with items separated by commas) - an array of strings. I want to convert to this class: ``` public class MyJob { public string description; public string[] contacts; public string enabled; } ``` when i try to assign just to a string (changing the above to this: public string contacts; ) using the JavascriptSerializer(): ``` var serializer = new JavaScriptSerializer(); string contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts; ``` I get this error in the cases where its an array: Type 'System.String' is not supported for deserialization of an array. what is the best way to go about deserializing this to handle the case of: - a string - an array of strings. for the contact field. I am happy to put any conditional logic needed . . I tried this: ``` var contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts; if (contacts is string) { jobInfo.contacts = contacts; } else { jobInfo.contacts = String.Join("; ", contacts ); } ``` but that didn't seem to fix as i am still getting the error above when its an array

Original source

Related problems