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 of fields in that REST
-service result changes depending on the information available.
An example: A Movie always has some screen captures (images), actors and directors. Depending on the movie in question, there might be one or more images, one or more actors and one or more directors. Sample JSON for a couple of cases:
{
"title": "Movie title",
"images": [
"http://www.url.com/img_0.jpg",
"http://www.url.com/img_1.jpg",
"http://www.url.com/img_2.jpg",
"http://www.url.com/img_3.jpg",
"http://www.url.com/img_4.jpg"
],
"actors": [
"Steven Berkoff",
"Nikolaj Coster-Waldau",
"Julie Cox"
],
"directors": "Simon Aeby"
},
{
"title": "Another movie",
"images": "http://www.url.com/img_1.jpg",
"actors": "actor 1"
"directors": [
"Justin Bieber",
"Justin Timberlake"
]
}
The question is, using JSON.net, how can I create a converter that deals with this problem? I've been scouring the internet, but still haven't found a solution.
Another spin on the same question: If a field is either a List of strings or a simple string, how do I make JSON.NET create a List either way (and if just a simple string, create a list with one member)
EDIT: This REST-service is out of my control
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:
Sample usage:
m1_directory is a list with a single element, m2_directors is a list with two elements.
Ok, I did it for fun, but don't think is useful or the best way, anyway...Declaring the "dynamic" attributes as object and then create methods to obtain the properties as something like ImagesAsList or ImagesAsString. I did it with Extension Methods.....
Class
Extension Methods
EDIT
After reading @yamen comments I did some changes like:
Class
Converter