Query JArray element property value using json.net

My jsonarray has a serialized list of products with id and name.

JArray jsonarray  = JArray.Parse(json);

var name = // Get value for Name property which has Id 1.

How can i do this?

+4
source share
2 answers

You can try using linq:

JArray jsonarray = JArray.Parse("[{'Id':3, 'Name': 'Product3'}, {'Id':1, 'Name': 'Product1'}, {'Id':2, 'Name': 'Product2'}]");

var name = jsonarray
    .FirstOrDefault(x => x.Value<int>("Id") == 1)
    .Value<string>("Name");

Please note that you must perform a null check because it FirstOrDefaultcan return null if the element with the property is Id == 1not found.

+4
source
 JArray jsonarray  = JArray.Parse(json);  
 var name = (string)jsonarray.Children().Single( p => (int)p["Id"] == 1)["Name"];

Catch potential InvalidOperationExceptionofSingle

0
source

Source: https://habr.com/ru/post/1607195/


All Articles