JSON.net-使用路径字符串写入JSON/JObject [英] JSON.net - Write into JSON / JObject using path string

查看:111
本文介绍了JSON.net-使用路径字符串写入JSON/JObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小工具,我们可以使用JObject.SelectToken(path)从JSON提取值.我们需要在运行时确定路径.完美运行.

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.

我现在需要做的是使用相同的路径字符串写回JSON(JObject或其他).我已经搜寻并搜寻了,但我找不到完全可以像SelectToken那样干净地进行读取的东西.

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.

(我也卡在3.5 CF中)

(I'm also stuck in 3.5 CF)

例如,类似:

... JObject read in already ...

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

... serialize it ... 

推荐答案

实际上会返回一个JToken,可以使用 JToken.Replace进行修改.您可以使用它替换JSON对象中的节点,从而使原始对象发生变化.

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" } ] }

这篇关于JSON.net-使用路径字符串写入JSON/JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆