Deserialize Json in C#
{
"person": "david",
"images": {
"usable_sizes": [
[
[150,
41
],
"image1.png"
],
[
[220,
61
],
"image2.png"
开发者_如何学Python ],
[
[220,
61
],
"image3.png"
]
],
"uploader": null
}
}
I am using a JavaScriptSerializer in C# to parse some JSON. The above is the string I get back from the webrequest. Calling Deserialize on the string puts the Person in the right place in the object, but I don't know what type to use for the array nested under "images." I am at a complete loss.
here is relevant code:
TopLevelObject topObj = new JavaScriptSerialize().Deserialize<TopLevelObj>(jsonStream);
public TopLevelObject
{
public string person;
public imgStruct images;
}
public class imgStructure
{
public List<string[,][]> available_sizes;
}
but that's not taking. I have tried a variety of other forms for the class, but can't get the deserialize to put the data in without proper keys. I have no ability to change the inbound JSON as I am consuming it from a third party.
This is what I believe your classes should look like:
public class RootObj
{
public string person;
public ImageDataObj images;
}
public class ImageDataObj
{
public object uploader;
public List<List<object>> usable_sizes
}
As you can see the inner list is a list of objects. That is because the list has items of different types: one is a list (numerical data [150, 41]) and the other is a string (image name). I do not think you can strongly type the inner list for that reason. Maybe it is worth examining on runtime (using the VS debugging tools) the structure of the objects inside the inner list and that could give you an indication of how to map it.
How the usable_images property type does look like if you take it to its detail is:
public List<List<Dictionary<List<int>,string>>> usable_sizes
but that is just a guess.
I would advise going to JSON.org and using one of their pre-built solutions.
精彩评论