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
1
  • what serializer are you using? or do you have flexibility to use any? IIRC this is a lot easier in, say, json.net - than via things like JavaScriptSerializer Commented Sep 6, 2013 at 8:21

1 Answer 1

4

Using 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();

or more dynamic versions

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>>>();
Sign up to request clarification or add additional context in comments.

1 Comment

Second one only i expected. How can read result values through loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.