Reputation: 315
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.
Upvotes: 5
Views: 6822
Reputation: 1543
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
Upvotes: 3
Reputation: 1407
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();
}
Upvotes: 0
Reputation: 18155
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
Upvotes: 0
Reputation: 174
By using a Dictionary
, you can use a dynamic record name as a key.
public class Root
{
[JsonProperty("results")]
public Result Results { get; set; }
}
public class Result
{
[JsonProperty("records")]
public Dictionary<string, Record> Records { get; set; }
}
public class Record
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
}
var data = JsonConvert.DeserializeObject<Root>(json);
Upvotes: 1