我需要从JSON字符串中获取所有动态名称和值。我将使用JSON字符串参数创建一个函数。该参数JSON字符串名称和值可以更改,但我需要从该JSON字符串中打印所有名称和值。
示例代码:
json : { "data":
[{
"id": "001",
"Name": "Somu",
"Address": "Erode",
},
{
"id": "002",
"Name": "Ajal",
"Address": "USA",
}]
}
我想通过in循环获取此JSON中的所有值。属性名称可能会更改或增加属性count.I需要从传递的JSON中获取所有值。
Expected Result : 1 st loop
Id = 001
Name =Somu
Address =Erode
2 nd loop
Id = 002
Name =Ajal
Address =USA
答案 0 :(得分:4)
使用Json.Net
string json = @"{ ""data"": [ { ""id"": ""001"", ""Name"": ""Somu"", ""Address"": ""Erode"", }, { ""id"": ""002"", ""Name"": ""Ajal"", ""Address"": ""USA"", }] }";
var result = JObject.Parse(json)
["data"]
.Select(x => new
{
id = (string)x["id"],
Name = (string)x["Name"],
Address = (string)x["Address"],
})
.ToList();
或更多动态版本
var result = JObject.Parse(json)
["data"]
.Select(x=> x.Children().Cast<JProperty>()
.ToDictionary(p=>p.Name,p=>(string)p.Value))
.ToList();
var result = JObject.Parse(json)["data"]
.ToObject<List<Dictionary<string,string>>>();