I have a situation where the JSON returned from a REST-service returns a list of Movie-objects, all specced out with a ton of information. A couple
You won't be able to serialise directly to an object, but you can do so manually without too much effort. JSON.Net contains LINQ to JSON. First define a method that will always return a list of type T even if the underlying JSON is not an array:
public List getSingleOrArray(JToken token)
{
if (token.HasValues)
{
return token.Select(m => m.ToObject()).ToList();
}
else
{
return new List { token.ToObject() };
}
}
Sample usage:
JObject m1 = JObject.Parse(@"{
""title"": ""Movie title"",
""images"": [
""http://www.url.com/img_0.jpg"",
""http://www.url.com/img_1.jpg""
],
""actors"": [
""Steven Berkoff"",
""Julie Cox""
],
""directors"": ""Simon Aeby""
}");
JObject m2 = JObject.Parse(@"{
""title"": ""Another movie"",
""images"": ""http://www.url.com/img_1.jpg"",
""actors"": ""actor 1"",
""directors"": [
""Justin Bieber"",
""Justin Timberlake""
]
}");
IList m1_directors = getSingleOrArray(m1["directors"]);
IList m2_directors = getSingleOrArray(m2["directors"]);
m1_directory is a list with a single element, m2_directors is a list with two elements.