1

I'm getting an array of items from Web API (lines before this are omitted):

var cars = JArray.Parse(response.Content.ReadAsStringAsync().Result)

Inside the cars JArray it looks like this:

"cars": [{
            "id": 1,
            "make": "Audi",
            "color": "red"
        }, {
            "id": 2,
            "make": "Mercedes",
            "color": "red"
        }, {
            "id": 3,
            "make": "Ford",
            "color": "yellow"
        }]

I would like to update the color of Ford to red if Audi is also red.

How can I do that with C# and Json.NET?

2
  • You can use json path along with json token Commented Jul 1, 2021 at 13:34
  • eeek dont do .Result on an async. Recipe for disaster. Commented Jul 1, 2021 at 14:32

1 Answer 1

1

The JSON you provided is not valid for me to parse, so ive made an assumption to demonstrate. which wraps your sample in a root JSON object.

You can query the JOBject using keys. i.e to access cars propery in the JSON you can use o["cars"]. With this approach you can see i use a bit of Linq to figure out if Audi is red, and if so, you can perform direct modifications to the o object and set values accordingly.

This is the most basic approach, without any further code.

void Main()
{
    var json = @"
    {
        ""cars"": [
            { ""id"": 1, ""make"": ""Audi"", ""color"": ""red"" }, 
            { ""id"": 2, ""make"": ""Mercedes"", ""color"": ""red"" }, 
            { ""id"": 3, ""make"": ""Ford"", ""color"": ""yellow"" }
        ]
    }";

    var jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
    var jArray = jObject["cars"] as JArray;

    Console.WriteLine("Before: " + JsonConvert.SerializeObject(jObject));

    var audiIsRed = jArray.Any(car => car.Value<string>("make").Equals("Audi") && car.Value<string>("color").Equals("red"));

    if (audiIsRed)
    {
        jArray.First(c => c.Value<string>("make").Equals("Ford"))["color"] = "red";
    }

    Console.WriteLine("After: " + JsonConvert.SerializeObject(jObject));
}

An alternative could be making a POCO to deserialize the results, which would contain, for example a List<Car> and then you could do all modifications with C# and no JSON.NET then serialize that result back to JSON.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.