我有以下字符串
{
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}
]
}
转换回json
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(parsedString);
我的问题是:
如何访问每个json属性,例如Something.Href
以提取1.jpg
,2.jpg
或仅Id
属性?
答案 0 :(得分:5)
我建议使用&#34; LINQ to JSON&#34;而不是DeserializeObject
,个人 - 虽然这可能只是因为有更多的经验:
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"]);
}
}
}
话说回来,你可以很好地使用DeserializeObject
,只需动态访问成员:
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);
}
}
}