2013-06-04 33 views
-1

我可以知道如何解析JSON聲明如下..... JSON是雅虎OAuth聯繫人列表的一部分。c#JavaScriptSerializer上包含字符串+字典的JSON

JSON:

"fields":[{     
       "id":2, 
       "type":"nickname", 
       "value":"Hello" 
      }, 
      { 
       "id":3, 
       "type":"email", 
       "value":"[email protected]" 
      }, 
      {  
       "id":1, 
       "type":"name", 
       "value":{ 
        "givenName":"Otopass", 
        "middleName":"Test", 
        "familyName":"Hotmail" 
        }, 
      }], 

C#對象:

private class fields 
    { 
     public string id { get; set; } 
     public string type { get; set; } 
     //public string value { get; set; }      //Stuck At Here !!!! 
     //public Dictionary<string, string> value { get; set; } //Stuck At Here !!!! 
    } 

如何解析 「值」?因爲它是字符串&的組合類型。

+0

退房類似的問題的http:/ /stackoverflow.com/questions/6416950/serializing-dictionaries-with-javascriptserializer –

+0

我不太瞭解解析json,但我可以告訴你,你不能在同一個類中有兩個字段具有相同的名稱,所以在你的中有一個字符串和Dictionary命名值fields類將拋出編譯器錯誤。 –

+0

您可能想要查看支持'dynamic'類型的JSON解串器。 – wgraham

回答

0

我不能使用JavaScriptSerializer回答這個問題,但你可以使用它json.Net和LINQ做

var jObj = JObject.Parse(json); 
var fields = jObj["fields"] 
       .Select(x => new Field 
       { 
        Id = (int)x["id"], 
        Type = (string)x["type"], 
        Value = x["value"] is JValue 
          ? new Dictionary<string,string>(){{"",(string)x["value"]}} 
          : x["value"].Children() 
             .Cast<JProperty>() 
             .ToDictionary(p => p.Name, p => (string)p.Value) 
       }) 
       .ToList(); 


private class Field 
{ 
    public int Id { get; set; } 
    public string Type { get; set; } 
    public Dictionary<string, string> Value { get; set; }  
} 

PS:我固定的部分JSON字符串作爲

string json = 
@"{""fields"":[ 
    {     
     ""id"":2, 
     ""type"":""nickname"", 
     ""value"":""Hello"" 
    }, 
    { 
     ""id"":3, 
     ""type"":""email"", 
     ""value"":""[email protected]"" 
    }, 
    {  
     ""id"":1, 
     ""type"":""name"", 
     ""value"":{ 
      ""givenName"":""Otopass"", 
      ""middleName"":""Test"", 
      ""familyName"":""Hotmail"" 
      } 
    } 
]}"; 
+0

哦..謝謝...我現在正在嘗試。 'jObj = Newtonsoft.Json.Linq'?它不包含'Select'的定義 – user2402624

+0

@ user2402624你所需要的只是'使用Newtonsoft.Json;'和'使用Newtonsoft.Json.Linq;' – I4V

+0

好的,謝謝。我將繼續研究並在稍後更新結果。 – user2402624