JSON.net - Write into JSON / JObject using path string

﹥>﹥吖頭↗ 提交于 2019-12-10 23:33:53

问题


I have a little utility where we extract values from JSON using JObject.SelectToken(path). We need to determine the paths at run-time. Works perfectly.

What I now need to do is to write back into the JSON (JObject or other) using the same path string. I've hunted and searched and I can't quite find if there is anything that does this quite as cleanly as SelectToken does for reading.

(I'm also stuck in 3.5 CF)

For example, something like:

... JObject read in already ...

var theJToken = theJObject.SelectToken("animals.cat[3].name");
theTJoken.SetValue("Bob"); // Of course this doesn't exist

... serialize it ... 

回答1:


JToken.SelectToken actually returns a JToken which can be modified using JToken.Replace. You can use that to replace the node within your JSON object, mutating the original object.

JObject o = JObject.Parse(@"{ 'cats': [
                { 'name': 'cat 1' },
                { 'name': 'cat 2' },
                { 'name': 'cat 3' } ] }");

// get the token
JToken secondCatName = o.SelectToken("cats[1].name");

// replace the name
secondCatName.Replace("meow");

// and the original object has changed
Console.WriteLine(o.ToString());
// { "cats": [ { "name": "cat 1" }, { "name": "meow" }, { "name": "cat 3" } ] }


来源:https://stackoverflow.com/questions/31929433/json-net-write-into-json-jobject-using-path-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!