Reputation: 163
How can I iterate over the images
in JSON of following format? Length of images
collection can be arbitrary. Can I manipulate it to make it a list, or what options do I have to parse this?
images: {
0: {
filename: "image1.jpg"
},
1: {
filename: "image2.jpg"
},
2: {
filename: "image3.jpg"
},
}
Upvotes: 2
Views: 226
Reputation: 163
I ended up figuring it out - although may not be best practice it worked in this case
var imageHoldingList = new List<VehicleImagesModel>();
var connectionResponse = JsonConvert.DeserializeObject<dynamic>(results);
var jImage = connectionResponse["response"]["vehicles"]["images"].Children();
foreach (var image in jImage)
{
var h = new VehicleImagesModel
{
Filename = image.First.filename.ToString(),
Caption = image.First.caption.ToString()
};
imageHoldingList.Add(h);
}
Upvotes: 1
Reputation: 1232
You can do this with vanilla javascript like this:
for (objectName in data["images"]) {
html += data["images"][objectName]["filename"] + "<br />"
}
Full HTML file example below
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="result"></div>
<script type="text/javascript">
var data = {
"images": {
"0": {
"filename": "image1.jpg"
},
"1": {
"filename": "image2.jpg"
},
"2": {
"filename": "image3.jpg"
}
}};
var html = '';
for (objectName in data["images"]) {
html += data["images"][objectName]["filename"] + "<br />"
}
document.getElementById("result").innerHTML = html;
</script>
</body>
</html>
Upvotes: 1
Reputation: 29186
If you have a read of this SO question, you'll notice that JSON.NET
is a recommended library to use for situations like this.
You could try using the DataContractJsonSerializer
to create objects from JSON input, but when I tried it just now, I couldn't get it to work with a collection of items in the JSON string.
Upvotes: 1
Reputation: 1218
One possible solution would be to create a dynamic
representation of your json:
dynamic jsonData = JsonConvert.DeserializeObject(@"{
images: {
0: {
filename: ""image1.jpg""
},
1: {
filename: ""image2.jpg""
},
2: {
filename: ""image3.jpg""
}
}
}");
foreach(var item in jsonData["images"])
{
//Do something
}
Upvotes: 1