如何以Path为键将JSON对象转换为字典 [英] How do I convert a JSON object into a dictionary with Path being the key

查看:74
本文介绍了如何以Path为键将JSON对象转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Newtonsoft.Json如何将JSON对象转换为以Path为键的字典?

Using Newtonsoft.Json how do I convert a JSON object into a dictionary with Path being the key?

IDictionary<string, object> FlattenJson(string Json)
{
  JToken Input = JToken.Parse(Json);

  ... magic ...

  return Result;
}

字典的键应为JToken.Path值,字典的值应为本机"格式的实际值(字符串为字符串,整数为long等).

Key of the dictionary shall be the JToken.Path value and Value of the dictionary shall be the actual value in its "native" format (string as string, integer a long, etc).

"message.body.titles [0] .formats [0] .images [0] .uri" =>"I/41SKCXdML._SX160_SY120_.jpg" "message.body.titles [0] .formats [0] .images [0] .widthPx" => 0 "message.body.titles [0] .customerReviewsCollectionIncluded" =>否 ...

"message.body.titles[0].formats[0].images[0].uri" => "I/41SKCXdML._SX160_SY120_.jpg" "message.body.titles[0].formats[0].images[0].widthPx" => 0 "message.body.titles[0].customerReviewsCollectionIncluded" => False ...

是否有适用于任意JSON的现成可用的东西?

Is there anything out-of-the-box that works for arbitrary JSON?

推荐答案

您需要递归遍历Json.NET层次结构,挑选原始值(类型为

You need to recursively traverse the Json.NET hierarchy, pick out the primitive values (which have type JValue), and store their values in the dictionary, like so:

public static class JsonExtensions
{
    public static IEnumerable<JToken> WalkTokens(this JToken node)
    {
        if (node == null)
            yield break;
        yield return node;
        foreach (var child in node.Children())
            foreach (var childNode in child.WalkTokens())
                yield return childNode;
    }

    public static IDictionary<string, object> ToValueDictionary(this JToken root)
    {
        return root.WalkTokens().OfType<JValue>().ToDictionary(value => value.Path, value => value.Value);
    }
}

然后称呼它

var Result = Input.ToValueDictionary();

请注意,整数将存储为Int64.

Note that integers will be stored as Int64.

这篇关于如何以Path为键将JSON对象转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆