最近我正在尝试制作一个 json 编辑器(与 treeview 一起使用),我做了更改值函数,我也可以更改一些键,但我不能在对象中设置键。 我可以设置值:
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 及其父代。
在这种情况下,您希望将“替换”视为:
- Add the old value by new key
- Remove the old key/value pair
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");
关于c# - 在 Json 中更改属性的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40002773/