如何遍历字典以获取键名并将其传递给字符串 [英] How to iterate through a dictionary to get and pass key name to string
问题描述
我想遍历存储嵌套JSON的C#字典,以检索字典键名并将其以"key1:key1-1:key1-1-1"的形式传递给字符串.
I'd like to iterate through a C# dictionary storing nested JSON to retrieve and pass the dictionary key name to a string, in the form of "key1:key1-1:key1-1-1".
此后,将创建一个新字典,以使用专门安排的字符串作为其键.
After that, a new dictionary is created to use the specially arranged string as its keys.
最后,desiredDictionary ["key:key:key"] = originalDictionary ["key"] ["key"] ["key"].
Finally, desiredDictionary["key:key:key"] = originalDictionary["key"]["key"]["key"].
请具体说明我的歉意,我对C#IEnumerable类和JSON不熟悉.
Please make the answer specific, my apology that I'm new to C# IEnumerable class and JSON.
我已将JSON数据存储到字典中,示例JSON如下所示.
I've stored the JSON data into a dictionary, the sample JSON is given below.
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
......
string jsonText = File.ReadAllText(myJsonPath);
var jss = new JavaScriptSerializer();
//this is the dictionary storing JSON
var dictJSON = jss.Deserialize<Dictionary<string, dynamic>>(jsonText);
//this is the dictionary with keys of specially arranged string
var desiredDict = new Dictionary<string, string>();
......
......
//Here is a sample JSON
{
"One": "Hey",
"Two": {
"Two": "HeyHey"
}
"Three": {
"Three": {
"Three": "HeyHeyHey"
}
}
}
我需要有关字典键名检索,字符串完成和新字典值传递的过程的帮助. 根据给定的JSON,desiredDict ["Three:Three:Three"] = dictJSON ["Three"] ["Three"] ["Three"] ="HeyHeyHey", 该解决方案有望应用于任何类似的JSON.
I need help with the process for dictionary key name retrieval, string completion, and new dictionary value passing. According to the given JSON, desiredDict["Three:Three:Three"] = dictJSON["Three"]["Three"]["Three"] = "HeyHeyHey", The solution is expected to apply on any similar JSON.
推荐答案
您可以使用递归方法来获取JObject并从中生成扁平化的字典,如下所示:
You can use a recursive method to take a JObject and produce a flattened dictionary from it like so:
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(JObject data, string path = null)
{
// path will be null or a value like Three:Three: (where Three:Three is the parent chain)
// go through each property in the json object
foreach (var kv in data.Properties())
{
// if the value is another jobject, we'll recursively call this method
if (kv.Value is JObject)
{
var childDict = (JObject)kv.Value;
// build the child path based on the root path and the property name
string childPath = path != null ? string.Format("{0}{1}:", path, kv.Name) : string.Format("{0}:", kv.Name);
// get each result from our recursive call and return it to the caller
foreach (var resultVal in NestedJObjectToFlatEnumerable(childDict, childPath))
{
yield return resultVal;
}
}
else if (kv.Value is JArray)
{
throw new NotImplementedException("Encountered unexpected JArray");
}
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, kv.Name), Convert.ToString(kv.Value));
}
}
}
用法:
var json = "{\"One\":\"Hey\",\"Two\":{\"Two\":\"HeyHey\" },\"Three\":{\"Three\":{\"Three\":\"HeyHeyHey\"}}}";
var jObj = JsonConvert.DeserializeObject<JObject>(json);
var flattened = FlattenJObjectToDictionary(jObj);
它利用 yield return
以单个IEnumerable<KeyValuePair<string, string>>
的形式返回递归调用的结果,然后以平面字典的形式返回该结果.
It takes advantage of yield return
to return the results of the recursive call as a single IEnumerable<KeyValuePair<string, string>>
and then returns that as a flat dictionary.
注意事项:
- JSON中的数组将引发异常(请参见
else if (kv.Value is JArray)
) - 用于处理实际值的
else
部分假定所有值都可以使用Convert.ToString(kv.Value)
转换为字符串.如果不是这种情况,则您将不得不为其他方案编写代码.
- Arrays in JSON will throw an exception (see
else if (kv.Value is JArray)
) - The
else
part for handling the actual values assumes that all values are convertible to string usingConvert.ToString(kv.Value)
. If this is not the case, you will have to code for extra scenarios.
这篇关于如何遍历字典以获取键名并将其传递给字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!