Madhatter5501
Madhatter5501

Reputation: 163

How to parse JSON and iterate over it?

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

Answers (4)

Madhatter5501
Madhatter5501

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

Allan McLemore
Allan McLemore

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

Jason Evans
Jason Evans

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

ChrisK
ChrisK

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

Related Questions