gpt4 book ai didi

c# - 将 JSON 值存储到具有有序键名的字典中

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:57 25 4
gpt4 key购买 nike

这是一个基于How to iterate through a dictionary to get and pass key name to string的问题,下面给定的代码遍历一个 JSON,获取键名和 JArray 索引并将它们有序地传递给 JSON 路径的字符串,最后它返回一个字典(有序字符串,JsonValue),字典键名应该像这样排序“key1:key1-1:0”,表示 desiredDictionary["key1:key1-1:0"] = commonDictionary["key1"]["key1-1"][0]。

根据下面的JSON,如果“五”:{“ArrayInFive”:[“elem1”,“elem2”]}被删除,它工作正常。

C#代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
......
static void Main(string[] args)
{
var json = File.ReadAllText(@myJsonPath);
var jObj = JsonConvert.DeserializeObject<JObject>(json);

var desiredDict = FlattenJObjectToDictionary(jObj);


foreach (var key in desiredDict.Keys)
{
Console.WriteLine(key + " : " + desiredDict[key]);
}


Console.Read();
}

private static IDictionary<string, string> FlattenJObjectToDictionary(JObject obj)
{
// obtain a key/value enumerable and convert it to a dictionary
return NestedJObjectToFlatEnumerable(obj, null).ToDictionary(kv => kv.Key, kv => kv.Value);
}


private static IEnumerable<KeyValuePair<string, string>> NestedJObjectToFlatEnumerable(object data, string path = null)
{
JObject jObject = (JObject)data;
var jOP = jObject.Properties();
foreach (var jop in jOP)
{
if (jop.Value is JObject)
{
var child = (JObject)jop.Value;

// build the child path based on the root path and the property name
string childPath = path != null ? string.Format("{0}{1}:", path, jop.Name) : string.Format("{0}:", jop.Name);

// get each result from our recursive call and return it to the caller
foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
{
yield return resultVal;
}
}
else if (jop.Value is JArray)
{
var jArray = (JArray)jop.Value;
for (int i = 0; i < jArray.Count; i++)
{
var child = jArray[i];

// build the child path based on the root path and the JArray index
string childPath = path != null ? string.Format("{0}{1}:{2}:", path, jop.Name, i.ToString()) : string.Format("{0}:{1}:", jop.Name, i.ToString());

// get each result from our recursive call and return it to the caller
foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
{
yield return resultVal;
}
}
}
else
{
// this kind of assumes that all values will be convertible to string, so you might need to add handling for other value types
yield return new KeyValuePair<string, string>(string.Format("{0}{1}", path, Convert.ToString(jop.Name)), Convert.ToString(jop.Value));
}
}

}

JSON

{
"One": "Hey",
"Two": {
"Two": "HeyHey"
},
"Three": {
"Three": {
"Three": "HeyHeyHey"
}
},
"Four": [
{
"One": "Hey"
},
{
"Two":
{
"Two": "HeyHey"
}
}
],
"Five": {
"ArrayInFive": [ "elem1", "elem2" ]
}
}

我希望

desiredDictionary["Five"]["ArrayInFive"][0] = "elem1"

desiredDictionary["Five"]["ArrayInFive"][1] = "elem2"

但是弹出“无法将 JValue 转换为 JObject”的异常,我需要一些代码更正方面的帮助,也许是整个程序。

最佳答案

NestedJObjectToFlatEnumerable 中的 JArray 对象的处理更改为:

else if (jop.Value is JArray)
{
var jArray = (JArray)jop.Value;
for (int i = 0; i < jArray.Count; i++)
{
var child = jArray[i];

if (child is JValue)
{
// return JValue objects directly as array elements instead of as objects in the array with their own property-value pairs
yield return new KeyValuePair<string, string>(string.Format("{0}{1}:{2}", path, jop.Name, i.ToString()), Convert.ToString(((JValue)child).Value));
}
else
{
// build the child path based on the root path and the JArray index
string childPath = path != null ? string.Format("{0}{1}:{2}:", path, jop.Name, i.ToString()) : string.Format("{0}:{1}:", jop.Name, i.ToString());

// get each result from our recursive call and return it to the caller
foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
{
yield return resultVal;
}
}
}
}

这处理数组元素是 JValue 而不是具有自己的属性值对的对象的情况,方法是将元素作为数组的属性返回,属性名称由数组给出索引(连接到数组路径上)。

关于c# - 将 JSON 值存储到具有有序键名的字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56884455/

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