Currently I'm facing the following issue when I try to deserialize a json string that I receive from a 3rd party (--> I cannot change the received json string by myself) with Newtonsoft.Json:
The json contains a dictionary (and some other entries that I don't list here):
"food": {
"Menu 1": "abc",
"Menu 2": "def"
}
I've created a class that contains the property (plus the properties that I didn't list here):
Dictionary<string, string> Food {get; set;}
In this case the desiralization of the json works fine. The problem occurs when food is empty:
{
"food": [],
}
In this case it seems that food is not a dictionary but an array. That's the reason why the desirialization fails with the following error:
Newtonsoft.Json.JsonSerializationException: "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'food'."
Is anybody out there who can help me to solve this problem, please?
EDIT The desiralization code:
public T DeserializeAPIResults<T>(string json)
{
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
return obj.GetValue("canteen").ToObject<T>();
}
EDIT 2 Full json with values:
{
"canteen": [
{
"name": "Canteen1",
"src": "a link",
"food": {
"Menu 1": "abc",
"Menu 2": "def",
"Menu 3": "ghi",
"Menu 4": "jkl",
"Menu 5": "mno"
}
},
{
"name": "Canteen2",
"src": "a link",
"food": {
"Menu 1": "abc",
"Menu 2": "def",
"Menu 3": "ghi"
}
},
{
"name": "Canteen3",
"src": "a link",
"food": {
"Line 1": "abc",
"Line 2": "def",
"Line 3": "ghi"
}
}
]
}
Full json without values:
{
"canteen": [
{
"name": "Canteen1",
"src": "a link",
"food": [],
},
{
"name": "Canteen2",
"src": "a link",
"food": [],
},
{
"name": "Canteen3",
"src": "a link",
"food": [],
}
]
}
EDIT 3 The class:
public sealed class Canteen
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("src")]
public string Src { get; set; }
[JsonProperty("food")]
public Dictionary<string, string> Food { get; set; }
public Canteen() { }
}
And the method call:
Canteen[] canteens = DeserializeAPIResults<Canteen[]>(json);