I have the following string
{
data: [
{"Href":"1.jpg","Id":1,"Height":55,"Width":55,"Index":0},
{"Href":"2.jpg","Id":2,"Height":55,"Width":55,"Index":1},
{"Href":"3.jpg","Id":3,"Height":55,"Width":55,"Index":2},
{"Href":"4.jpg","Id":4,"Height":55,"Width":55,"Index":3}
]
}
which is converted back to json
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(parsedString);
My question is:
How can I access each json attribute, for example Something.Href
to extract 1.jpg
, 2.jpg
or only Id
properties?
I would suggest using "LINQ to JSON" instead of DeserializeObject
, personally - although that may just due to having more experience with it:
using System;
using System.IO;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string text = File.ReadAllText("Test.json");
var json = JObject.Parse(text);
var data = json["data"];
foreach (var item in data)
{
Console.WriteLine(item["Href"]);
}
}
}
Having said that, you can use DeserializeObject
perfectly well, just accessing the members dynamically:
using System;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
string text = File.ReadAllText("Test.json");
var json = JsonConvert.DeserializeObject<dynamic>(text);
var data = json.data;
foreach (var item in data)
{
Console.WriteLine(item.Href);
}
}
}
See more on this question at Stackoverflow