JSON Question

Changing Key Of An Property in Json

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)

I can also set some keys:

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?

Answer Source

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;

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download