Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c# - Json.net rename properties

I have a string representing JSON and I want to rename some of the properties using JSON.NET. I need a generic function to use for any JSON. Something like:

public static void Rename(JContainer container, Dictiontionary<string, string> mapping)
{
  foreach (JToken el in container.Children())
  {
    JProperty p = el as JProperty;
    if(el != null && mapping.ContainsKey(p.Name))
    {
      // **RENAME THIS NODE!!**
    }

    // recursively rename nodes
    JContainer pcont = el as JContainer;
    if(pcont != null)
    {
      Rename(pcont, mapping);
    }
  }
}

How to do it??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest reconstructing your JSON with renamed properties. I don't think you should worry about speed penalties as it's usually not an issue. Here's how you can do it.

public static JToken Rename(JToken json, Dictionary<string, string> map)
{
    return Rename(json, name => map.ContainsKey(name) ? map[name] : name);
}

public static JToken Rename(JToken json, Func<string, string> map)
{
    JProperty prop = json as JProperty;
    if (prop != null) 
    {
        return new JProperty(map(prop.Name), Rename(prop.Value, map));
    }

    JArray arr = json as JArray;
    if (arr != null)
    {
        var cont = arr.Select(el => Rename(el, map));
        return new JArray(cont);
    }

    JObject o = json as JObject;
    if (o != null)
    {
        var cont = o.Properties().Select(el => Rename(el, map));
        return new JObject(cont);
    }

    return json;
}

And here's an example of usage:

var s = @"{ ""A"": { ""B"": 1, ""Test"": ""123"", ""C"": { ""Test"": [ ""1"", ""2"", ""3"" ] } } }";
var json = JObject.Parse(s);

var renamed = Rename(json, name => name == "Test" ? "TestRenamed" : name);
renamed.ToString().Dump();  // LINQPad output

var dict = new Dictionary<string, string> { { "Test", "TestRenamed"} };
var renamedDict = Rename(json, dict);
renamedDict.ToString().Dump();  // LINQPad output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...