Json.net rename properties(Json.net 重命名属性)
问题描述
我有一个表示 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;
}
下面是一个用法示例:
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
这篇关于Json.net 重命名属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Json.net 重命名属性
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01