I have a json as below.
{
"name": "",
"id": "test1",
"properties": {
"name1": [
{
"id": "test2",
},
{
"id": "test3"
}
}
],
"name3": [
{
"id": "test4"
}
],
"name5": [
{
"id": "test7"
}
],
"name7": [
{
"id": "test8"
}
]
}
}
In the above JSON. I am looking to extract values of all properties which has "id". so finally I need a list that has id values as below.
{"test2", "test3","test4","test7","test8"}
How I can implement this in C#. Thanks for any suggestions?
CodePudding user response:
Based on your mention of JsonConvert
it seems you are using Json.NET
. So one of the options is to use json path to extract needed values:
var js_str= ....;
var jToken = JToken.Parse(js_str);
var result = jToken.SelectTokens("$.properties.*.[*].id")
.Values()
.Select(value => value.Value<string>())
.ToList();
Or you can query you json with LINQ.
Or create model that represents your data. There is quite common convention for dictionaries to represent object so something like this will work:
public class Root
{
public Dictionary<string, List<Obj>> Properties { get; set; }
}
public class Obj
{
public string Id { get; set; }
}
var deserialized = JsonConvert.DeserializeObject<Root>(js_str);
var result = deserialized.Properties
.Values
.SelectMany(v => v)
.Select(obj => obj.Id)
.ToList();
CodePudding user response:
Using JToken.Parse does not need to create the classes, but as I guess you may need not only Ids but some another data too. In this case try this code that is using JsonConvert
var json="{\"name\":\"\",\"id\":\"test1\",\"properties\":{\"name1\":[{\"id\":\"test2\"},{\"id\":\"test3\"}],\"name3\":[{\"id\":\"test4\"}],\"name5\":[{\"id\":\"test7\"}],\"name7\":[{\"id\":\"test8\"}]}}";
var jD=JsonConvert.DeserializeObject<Root>(json);
var ids=jD.properties.Select(p =>p.Value.Select(v =>v.id ) ).SelectMany(i=> i).ToList();
output
["test2", "test3","test4","test7","test8"]
classes
public class Root
{
public string name { get; set; }
public string id { get; set; }
public Dictionary<string,Name[]> properties { get; set; }
}
public class Name
{
public string id { get; set; }
}