How do I convert a JSON object into a dictionary with Path being the key

让人想犯罪 __ 提交于 2019-12-11 13:41:21

问题


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;
}

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" => False ...

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


回答1:


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);
    }
}

And then call it like

var Result = Input.ToValueDictionary();

Note that integers will be stored as Int64.



来源:https://stackoverflow.com/questions/27749114/how-do-i-convert-a-json-object-into-a-dictionary-with-path-being-the-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!