更改Json中的属性的键 [英] Changing Key Of An Property in Json

查看:139
本文介绍了更改Json中的属性的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些天,我正试图制作一个json编辑器(可与treeview一起使用),我确实更改了值函数,也可以更改某些键,但是我无法在对象中设置键. 我可以设置值:

I'm trying to make a json editor(works with treeview) these days, i did changing value function, i can change some keys as well, but i cant set keys in objects. I can set the value:

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);
}

但是我该如何设置按键? 问候.

But how can i set the keys? Regards.

推荐答案

您不需要通过ref传递原始根对象,也根本不需要原始根.您只关心JToken及其父代.

You don't need to pass the original root object by ref and you don't need the original root at all. All you care about is the JToken and its parent.

在这种情况下,您想将替换"视为:

In this case, you want to think of "replacement" as:

  • 通过新键添加旧值
  • 删除旧的键/值对
  • 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,这也是安全的.您可以这样称呼它:

We can assume that if you are replacing a key for a key value pair, that the object is a JProperty token. In addition, if we are replacing keys, it is also safe to assume the parent is a JObject. You can call it as such:

var json = "{ 'key1': 'val1' }";
JObject parsedObj = JsonConvert.DeserializeObject<JObject>(json);
SetKey(parsedObj, parsedObj.First, "key2");

这篇关于更改Json中的属性的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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