5

I am looking to parse JSON into a C# List. The problem is that the data I am trying to parse is not coming in Array format. Following is the sample JSON

   {
   "results":{
      "records":{
         "record:8545314564":{
            "name":"record 1",
            "description":"description for record 1"
         },
         "record:2254698789":{
            "name":"record 2",
            "description":"description for record 2"
         },
         "record:7454687851":{
            "name":"record 3",
            "description":"description for record 3"
         }
      }
   }
}

My Model class looks something like this

public class Record
{
    public string Name { get; set; }

    public string Description { get; set; }
}

What I am looking for is to create a

List<Record> Records

I don't care about the name of the records child node (i.e record:8545314564, record:2254698789 etc). All I care about is the name and description property inside each record node.

I would really appreciate if someone can please provide a sample code in C# to achieve this desired output.

3 Answers 3

3

And another alternative:

using Newtonsoft.Json.Linq;
...
var jObject = JObject.Parse(yourJsonString);
var records = jObject["results"]["records"]
    .Children()
    .Children()
    .Select(i => i.ToObject<Record>())
    .ToList();

You can find relevant Json.NET documentation here: https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm

Sign up to request clarification or add additional context in comments.

Comments

0

You could do the following.

var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
var recordCollection = result.results.records.Values.ToList();

Where RootObject is defined as

public class RootObject
{
    public ResultObject results { get; set; }
}

public class ResultObject
{
    public Dictionary<string, RecordObject> records { get; set; }
}

public class RecordObject
{
    public string name { get; set; }
    public string description { get; set; }
}

Output

enter image description here

Comments

0

You can parse the Json and then iterate through the tokens for each property value.

// assuming json is your json string
JObject obj = JObject.Parse(json);
JToken sec = obj["results"]["records"];

 foreach (JToken token in sec)
 {
      string name = token.First()["name"].ToString();
      string description = token.First()["description"].ToString();
 }

Comments

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.