1

I need to get all dynamic name and values from JSON string. I am going to create one function with JSON string parameter. that parameter JSON string name and values can change, But I need to print all names and values from that JSON string.

Example code :

json : {   "data": 
       [{
         "id": "001",
         "Name": "Somu",
         "Address": "Erode",
        },
        {
         "id": "002",
         "Name": "Ajal",
         "Address": "USA",
        }]
       }

I want to Get all values from this JSON with in loop. Property name may change or increase property count.I need to get all values from passed JSON.

 Expected Result :  1 st loop
            Id = 001
            Name =Somu
            Address =Erode
         2 nd loop
            Id = 002
            Name =Ajal
            Address =USA
4

1 回答 1

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>>>();
于 2013-09-06T08:23:33.237 回答