我想遍历存储嵌套JSON的C#字典,以检索字典键名并将其以“ key1:key1-1:key1-1-1”的形式传递给字符串。
此后,将创建一个新词典,以使用专门安排的字符串作为键。
最后,desiredDictionary [“ key:key:key”] = originalDictionary [“ key”] [“ key”] [“ key”]。
请具体说明我的歉意,我对C#IEnumerable类和JSON不熟悉。
我已将JSON数据存储到字典中,示例JSON如下所示。
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。
答案 0 :(得分:2)
您可以使用递归方法来获取JObject并从中生成一个扁平化的字典,如下所示:
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>>
返回,然后将其作为平面字典返回。
注意事项:
else if (kv.Value is JArray)
)else
部分假定所有值都可以使用Convert.ToString(kv.Value)
转换为字符串。如果不是这种情况,您将不得不为其他方案编写代码。