简体   繁体   中英

Update JObject with JToken

Say I have some JSON

{
    "name": "John"
    ... other properties
}

It could also be like

{
    "person": {
        "name": "John"
    }        
    ... other properties
}

And this code to look for the name field.

var obj = JObject.Parse(json);
var token = obj.SelectToken("$..name");            
token = "James";

After getting it, I want to set it to another value and put it back into the JSON to get

{
    "person": {
        "name": "James"
    }        
    ... other properties
}

or

{
    "person": {
        "name": "James"
    }        
    ... other properties
}

How can I put the JToken back into the JObject?

Please try this:

var o = JObject.Parse(json);
o["person"]["name"] = "James";
var backToJson = o.ToString(Formatting.None);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM