I am dealing with a REST-service that, depending on the information given to it (it’s a search service), gives back elements with either string elements or a list of string elements. An example could be searching for an item that has zero or more images – saved as url-strings. My model contains the following property to deal with my example:
private List<string> _Images = new List<string>();
[DataMember(Name="images", IsRequired=false)]
public List<string> Images
{
get
{
return _Images;
}
set
{
_Images = value;
onPropertyChanged("Images");
}
}
Sample JSON with several images:
{
"id": 24955,
"title": "Conan the Barbarian",
"duration": 105,
"hd": false,
"trailer": "800/BM_6305_800_tr.wmv",
"images": [
"http://website.com/images/conanthebar_1.jpg",
"http://website.com/images/conanthebar_2.jpg",
"http://website.com/images/conanthebar_3.jpg",
"http://website.com/images/conanthebar_4.jpg",
"http://website.com/images/conanthebar_5.jpg",
"http://website.com/images/conanthebar_6.jpg"
]
}
Sample JSON with ONE image:
{
"id": 24955,
"title": "Conan the Barbarian",
"duration": 105,
"hd": false,
"trailer": "800/BM_6305_800_tr.wmv",
"images": "http://website.com/images/conanthebar_6.jpg"
}
Now, my question is, when I’m using DataContractJsonSerializer, how will this be handled? If the image string of my incoming json is a single string (compared to an array / list of strings), will it convert it to a list of strings with only one member?
Finally, if this ISN’T the case (my theory is false), how could such a situation be handled?
Kris, if DataContractJsonSerializer is expecting an array or any IEnumerable of strings, it will actually expect something in the following format:
[ “str1”, “str2”, “str3”, …]
If it receives only a string, like below:
“str1”
it will actually throw an exception. It does not automatically convert this to an array, and there is no way to.
One workaround you have, however, is if you declare “Images” to be of type System.Object. If you do this, serialization will work the same. Deserialization will work exactly how you want it — it will deserialize to an array of strings if encounters an array, and it will deserialize to a System.string if it encounters a string.