2016-03-03 90 views
0

我想從鍵值對中的節點的基礎下從JSON提取值。我需要將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" 
      } 
     } 
    } 
}] 
+0

如果您不關心強類型解決方案,請嘗試使用'dynamic'。它將允許您訪問您提供的任何財產。 –

+0

可以給我的代碼行,我cn使用 – John

+0

'dynamic foo = JObject.Parse(jsonText); string bar = foo.Bar;'see [link](https://thewayofcode.wordpress.com/2012/09/18/c-dynamic-object-and-json-serialization-with-json-net/) –

回答

0

你可以做一個遞歸擴展方法拼合JToken層次字典:

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