如何将值从JSON存储到键值对

时间:2016-03-03 09:58:23

标签: c# json json.net

我试图根据键值对中的节点从下面的JSON中获取值。我需要在列表或集合中存储JSON字段的值。我尝试使用下面的代码,但它没有提供所需的输出。我怎样才能做到这一点?

截至目前,我正在这样做:

HttpPostedFileBase JSfile = Request.Files["UploadedJSFile"];

if ((JSfile != null) && (JSfile.ContentLength > 0) && !string.IsNullOrEmpty(JSfile.FileName))
{
   BinaryReader b = new BinaryReader(JSfile.InputStream);
   byte[] binData = b.ReadBytes(JSfile.ContentLength);

   string result = System.Text.Encoding.UTF8.GetString(binData);
   JArray jsonVal = JArray.Parse(result) as JArray;

   foreach (JObject content in jsonVal.Children<JObject>())
   {
      foreach (JProperty prop in content.Properties())
      {
         filters.Add(prop.Name, prop.Value.ToString());
      }
   }
}

但它没有给出所需的输出 我希望所有值都与节点类似:herobanner.landing.copies.watchvideo

这是我的JSON:

[{
    "country": "en-in",
    "heroBanner": {
        "landing": {
            "copies": {
                "watchVideo": "watch the video",
                "scrollDown": [
                    "READ INSPIRING STORIES",
                    ""
                ],
                "banner": [
                    "make your",
                    "first move this",
                    "valentine's Day"
                ]
            },
            "background": {
                "desktop": "assets/images/millions-hero-1.jpg"
            },
            "foreground": {
                "desktop": ""
            },
            "video": {
                "youtubeId": "buwcDIcFR8I"
            }
        }
    }
}]

1 个答案:

答案 0 :(得分:0)

您可以使用递归扩展方法将JToken层次结构展平为Dictionary:

public static class JsonExtensions
{
    public static Dictionary<string, object> Flatten(this JToken token)
    {
        var dict = new Dictionary<string, object>();
        Flatten(token, dict);
        return dict;
    }

    private static void Flatten(JToken token, Dictionary<string, object> dict)
    {
        switch (token.Type)
        {
            case JTokenType.Object:
                foreach (JProperty prop in token.Children<JProperty>())
                {
                    Flatten(prop.Value, dict);
                }
                break;

            case JTokenType.Array:
                foreach (JToken child in token.Children())
                {
                    Flatten(child, dict);
                }
                break;

            default:
                dict.Add(token.Path, ((JValue)token).Value);
                break;
        }
    }
}

然后像这样使用它,假设jsonVal是某种类型的JToken(例如JArray或JObject):

var dict = jsonVal.Flatten();
foreach (var kvp in dict)
{
    Console.WriteLine(kvp.Key + ": " + kvp.Value);
}

小提琴:https://dotnetfiddle.net/sVrM2e