gpt4 book ai didi

c# - 将平面字典序列化为多子对象 JSON

转载 作者:行者123 更新时间:2023-12-03 23:08:27 25 4
gpt4 key购买 nike

在 C# 中,我有一个扁平的 Dictionary<string, string>,其中键是 obj1/obj2/obj3 的形式,值是直接字符串。现在我想将其序列化为子对象,因此示例值:

var dict = new Dictionary<string, string> { {"foo/bar/baz1", "123" }, {"foo/baz", "456" }, { "foo/abc", "def" } };

应该导致:
{
"foo": {
"bar": {
"baz1": "123"
},
"baz": "456",
"abc": "def"
}
}

(可选)我想删除输出中“123”和“456”周围的引号,如果它们可以解释为数字或 bool 值。

我正在使用 Newtonsoft.JSON

最佳答案

您可以使用 JObject 方法将源字典解析为 JObject.FromObject 。然后遍历所有属性,使用 string.Split 拆分它们并递归解析为新的 JObject ,表示属性树。最后使用 JObject.Add 将此对象添加到目标对象,或者如果给定的键已存在则更新它

var dict = new Dictionary<string, string> { { "foo/bar/baz1", "123" }, { "foo/baz", "456" }, { "foo/abc", "def" } };
var source = JObject.FromObject(dict);
var dest = new JObject();

foreach (var property in source.Properties())
{
//split the name into parts
var items = property.Name.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
var item = items.FirstOrDefault();
if (string.IsNullOrEmpty(item))
continue;

//get JObject representing a properties tree
var result = WriteItems(items.Skip(1).ToList(), property.Value);

//check that destination already contains top property name (e.g. 'foo')
if (dest.ContainsKey(item))
{
(dest[item] as JObject)?.Add(result.First);
}
else
{
dest.Add(item, result);
}
}

Console.WriteLine(dest.ToString());

//local function to recursively go through all properties and create a result JObject
JObject WriteItems(IList<string> items, JToken value)
{
var item = items.FirstOrDefault();
items.RemoveAt(0);

if (!items.Any()) //no more items in keys, add the value
return new JObject(new JProperty(item, value));

return new JObject(new JProperty(item, WriteItems(items, value)));
}

它产生以下输出
{
"foo": {
"bar": {
"baz1": "123"
},
"baz": "456",
"abc": "def"
}
}

此外,上面的代码允许您处理具有任何深度的属性树。我不认为有一种内置的方法可以将 foo/bar/baz1 之类的结构序列化为 Json.NET 中的子对象

关于c# - 将平面字典序列化为多子对象 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60692733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com