JSON.NET重命名性能重命名、性能、JSON、NET

2023-09-03 07:06:06 作者:印记

我有一个字符串再presenting JSON和我要重新命名一些使用JSON.NET属性。我需要一个通用的功能,可以用于任何JSON。是这样的:

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

怎么办呢?

推荐答案

我会建议用更名的属性重构你的JSON。我不认为你应该担心的速度处罚,它通常不是一个问题。这里是你如何能做到这一点。

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