Search code examples
c#jsonjson.net

Append value to a Jtoken


Given the following JSON

{
    "Cars" [
        {
            "Mercedes-Benzz": {
                "A-class": "A160,A180"
                 "B-class": "B200"
            }
        }
    ]
}

I want to append a value and my JSON to be like :

{
    "Cars" [
        {
            "Mercedes-Benz": {
                "A-class": "A160,A180,A200"
                 "B-class": "B200"
            }
        }
    ]
}

Is there a way to do it?

var myjson= File.ReadAllText(filepath);
JObject myDocument = JObject.Parse(myjson);

var property = myDocument ["Cars"][0]["Mercedes-Benz"]["A-class"];
property.append("A200"); //<- This DO NOT WORK

File.WriteAllText(filepath,myDocument.ToString());

It will also be optimal, if there was a way to check if the value that I want to append already exists.


Solution

  • Do not use

    property.append()
    

    use something like

    var myvalue = propery.ToString();
    //code to edit this as you like
    property = myvalue;