I am attempting to only extract specific data from a json file if a name matches a certain value. For instance I want to only extract "gender": "man" etc where name = Joe
So only pull everything within the set of {} where name = Joe and ignore the rest of the data.
{
"Name": "Joe",
"gender": "man",
"address": "123"
},
{
"Name": "Rack",
"gender": "man",
"address": "456"
}
I have looked at similar questions but nothing answers this directly.
var rootInstance = JsonConvert.DeserializeObject<RootObject>(jsonString);
var result = //Do something here to filter data if name equals Joe
CodePudding user response:
I assume you are using a list of objects under your rootObject, let’s say subObjects, which is a list of subObject.
The following code piece would give you what you want:
var result = rootObject.subObjects.Where(x => string.Equals(x.Name, “Joe”).Select(y => y.Gender).ToList();
Now you have a result, containing a list of genders where the name is equal to Joe.
CodePudding user response:
Your json is invalid. You have to fix it. Assuming that it is an array
using Newtonsoft.Json;
var jsonParsed=JArray.Parse(json);
string searchName="Joe";
string gender=jsonParsed.Where(p =>(string) p["Name"]==searchName )
.Select(g=> (string)g["gender"])
.FirstOrDefault();