2010-11-13 85 views
1

我很無奈,我需要反序列化這種格式的JSON字符串到類中。使用JSON.NET反序列化JSON字符串

JSON字符串:

{"newNickInfo":{"2775040":{"idUser":2775040,"nick":"minci88","sefNick":"minci88","sex":2,"photon":"http:\/\/213.215.107.125\/fotky\/277\/50\/n_2775040.jpg?v=4","photos":"http:\/\/213.215.107.125\/fotky\/277\/50\/s_2775040.jpg?v=4","logged":false,"idChat":0,"roomName":"","updated":1289670130}}} 

類:

public class User 
{ 
public string idUser{get;set;} 
public string nick{get;set;} 
public string sefNick{get;set;} 
public string sex{get;set;} 
public string photon{get;set;} 
public string photos{get;set;} 
public bool logged{get;set;} 
public int idChat{get;set;} 
public string roomName{get;set;} 
public string updated{get;set;} 
} 

第一個問題是,類屬性必須是小寫,而第二個問題是我嘗試了很多方法,但我不知道該怎麼切json對象從這個json字符串中反序列化。 任何ides?感謝任何幫助。

還有一個問題,如果我想將這個json字符串反序列化到其中,那麼什麼格式會有c#類。

+0

你嘗試了什麼東西,你得到了什麼結果? – 2010-11-13 19:53:41

回答

0
using System.Web.Script.Serialization; 

var serializer = new JavaScriptSerializer(); 
var deserialized = serializer.Deserialize<Dictionary<string, Dictionary<string, User>>>(theJsonString); 
var theUser = deserialized["newNickInfo"]["2775040"]; 
+0

嗨Domenic,您的解決方案不起作用。嘗試,我得到編譯錯誤:System.Collections.Generic.Dictionary <字符串,System.Collections.Generic.Dictionary >'是一個'類型',但用於'變量' – 2010-11-14 12:12:55

+0

是的,我忘了關閉'>' ;現在就試試。 – Domenic 2010-11-14 20:28:09

1

看起來像你的JSON字符串是不正確的。看看這個

string json = @"[ 

    { 
     "newNickInfo": "2775040", 
     "idUser": "2775040", 
     "nick":"minci88", 
     "sefNick":"minci88", 
     "sex":2, 
     "photon":"http:\/\/213.215.107.125\/fotky\/277\/50\/n_2775040.jpg?v=4", 
     "photos":"http:\/\/213.215.107.125\/fotky\/277\/50\/s_2775040.jpg?v=4", 
     "logged":false, 
     "idChat":0, 
     "roomName":"", 
     "updated":"1289670130" 
    } 
]"; 



public class User 
{ 
[JsonProperty] 
public string idUser{get;set;} 
[JsonProperty] 
public string nick{get;set;} 
[JsonProperty] 
public string sefNick{get;set;} 
[JsonProperty] 
public string sex{get;set;} 
[JsonProperty] 
public string photon{get;set;} 
[JsonProperty] 
public string photos{get;set;} 
[JsonProperty] 
public bool logged{get;set;} 
[JsonProperty] 
public int idChat{get;set;} 
[JsonProperty] 
public string roomName{get;set;} 
[JsonProperty] 
public string updated{get;set;} 
} 


List<User> users = JsonConvert.DeserializeObject<List<User>>(json); 

User u1 = users[0]; 

Console.WriteLine(u1.nick); 
+0

嗨,使用JSONLint驗證器,字符串是好的http://www.jsonlint.com/。嘗試一下。 – 2010-11-13 21:04:43

0

我使用這個工具Jsonclassgenerator。它可以爲輸入的Json字符串生成C#類。你不必使用生成的確切類。但是您可以看到該課程的格式,並在您的項目中創建一個類似的課程。

+0

在發佈複製和粘貼樣板/逐字回答(http://stackoverflow.com/questions/4575445/c-sharp-class-to-parse-json-result/7996810#7996810)到多個問題時要小心,這些往往會被社區標記爲「垃圾」。 – Kev 2011-11-03 14:46:00