我有一个代表JSON的字符串,我想使用JSON.NET重命名一些属性。我需要一个通用函数来用于任何JSON。类似于:
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。我认为你不应该担心速度处罚,因为这通常不是问题。以下是你的操作方法。
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;
}
这里有一个用法示例:
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
我们使用这种方法。您可以使用JObject的SelectToken()找到您想要的属性。是的,它确实支持JsonPath。
public static class NewtonsoftExtensions
{
public static void Rename(this JToken token, string newName)
{
var parent = token.Parent;
if (parent == null)
throw new InvalidOperationException("The parent is missing.");
var newToken = new JProperty(newName, token);
parent.Replace(newToken);
}
}