问题
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
回答1:
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.
回答2:
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.
回答3:
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(',');
来源:https://stackoverflow.com/questions/10141610/in-c-sharp-how-can-i-deserialize-this-json-when-one-field-might-be-a-string-or-a