'find a match with an element in my class c#
I have the following JSON string
{ "Params": [ { "name": "id","value": "1234567" },
{ "name": "class","value": "six"}
],
"type":"general"}
and equivalent class as below
public class class1
{
public Param[] Params { get; set; }
public string Type { get; set; }
}
public class Param
{
public string Name { get; set; }
public string Value { get; set; }
}
How can I search if there is an object with name as id in Params array and how to fetch its value?
Solution 1:[1]
Include Newtonsoft.Json
using Newtonsoft.Json;
Then deserialize your json string to an object of class1, then search using linq.
string json = "{\"Params\": [ { \"name\": \"id\",\"value\": \"1234567\" },{ \"name\": \"class\",\"value\": \"six\"}],\"type\":\"general\"}";
// convert to object
var jsonObject = JsonConvert.DeserializeObject<class1>(json);
// filter
var result = jsonObject.Params.Where(p=> p.Name == "id" && p.Value == "1234567");
Solution 2:[2]
The Json.net documentation has a pretty good example you can use as well. It shows a way to do without necessarily converting to a C# object. See below
https://www.newtonsoft.com/json/help/html/queryinglinqtojson.htm
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jerdine Sabio |
| Solution 2 | Dharman |
