我有以下字符串
{
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}
]
}
Run Code Online (Sandbox Code Playgroud)
转换回json
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(parsedString);
Run Code Online (Sandbox Code Playgroud)
我的问题是:
我怎样才能访问每个JSON属性,例如Something.Href提取1.jpg,2.jpg或仅Id属性?
我建议使用"LINQ to JSON"而不是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"]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
话虽如此,你可以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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |