Mike Mike - 2 months ago 9
C# Question

Take out certain elements in a Json String

I have this Json snippet (simplified)

[
{
"ReferenceId": 0,
"MasterId": 1,
"BuildType": {
"DisplayName": null,
},
"Type": {
"DisplayName": null,
},
"IsActive": true,
"Name": "Product1",
"Id":1
},
{
"ReferenceId": 0,
"MasterId": 1,
"BuildType": {
"DisplayName": null,
},
"Type": {
"DisplayName": null,
},
"IsActive": false,
"Name": "Product2",
"Id":2
}
]


I want to intercept this string removed all the IsActive: false and return a string that represents a valid Json Array

So far I have

JArray jArrayResponse = JArray.Parse(response);
//json = jArrayResponse.Where(x => x["IsActive"].ToString() == "true").ToString();


The .ToString() just gives me "System.Ienumberable", and I am not even sure the Where clause is working yet.

Answer

You're not far off. The trick is to pass the IEnumerable<JToken> from the Where clause into a new JArray then convert that to string. Also, you can cast the IsActive JValues directly to bool:

JArray jArrayResponse = JArray.Parse(response);
var json = new JArray(jArrayResponse.Where(x => (bool)x["IsActive"])).ToString();

Fiddle: https://dotnetfiddle.net/lt9iWS

Comments