这些天我正在尝试制作一个 json 编辑器(与树视图一起使用),我确实更改了值函数,我也可以更改一些键,但我无法在对象中设置键。
我可以设置值:
SetValue(ref JObject main,JToken token,JToken newValue) {
//2nd argument is obj.SelectToken(node.Path)
token.Replace(newValue);
}
我还可以设置一些键:
SetKey(ref JObject main,JToken token,string newKey) {
//2nd argument is obj.SelectToken(node.Path)
//However, if token is in object, it seys the key of object because parent is object
(token.Parent as JProperty).Replace(newKey);
}
但我该如何设置按键呢?
问候。
您不需要通过 ref 传递原始根对象,并且根本不需要原始根。您所关心的只是 JToken 及其父代。
在这种情况下,您需要将“替换”视为:
public void SetKey(JObject parent, JToken token, string newKey)
{
var tokenProp = token as JProperty;
var oldKeyName = tokenProp.Name;
parent[newKey] = tokenProp.Value;
parent.Remove(oldKeyName);
}
我们可以假设,如果您要替换键值对的键,则该对象是 JProperty 令牌。此外,如果我们要替换键,也可以安全地假设父级是 JObject。您可以这样称呼它:
var json = "{ 'key1': 'val1' }";
JObject parsedObj = JsonConvert.DeserializeObject<JObject>(json);
SetKey(parsedObj, parsedObj.First, "key2");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)