2014-02-25 57 views
5

我有一個JSON字符串:反序列化的Json當對象的數量是未知

{ 
    "B" : 
    { 
     "JackID" : "1", 
     "Faction" : "B", 
     "Regard" : "24", 
     "Currency" : "1340", 
     "factionName" : "Buccaneer", 
     "factionKing" : "22", 
     "Tcurrency" : "0", 
     "currencyname" : "Pieces of Eight", 
     "textcolor" : "#FFFFFF", 
     "bgcolor" : "#000000" 
    }, 
    "P" : 
    { 
     "JackID" : "1", 
     "Faction" : "P", 
     "Regard" : "20", 
     "Currency" : "250", 
     "factionName" : "Privateer", 
     "factionKing" : "4", 
     "Tcurrency" : "0", 
     "currencyname" : "Privateer Notes", 
     "textcolor" : "#000000", 
     "bgcolor" : "#FFFF00" 
    }, 
    "N" : 
    { 
     "JackID" : "1", 
     "Faction" : "N", 
     "Regard" : "12", 
     "Currency" : "0", 
     "factionName" : "Navy", 
     "factionKing" : "7", 
     "Tcurrency" : "0", 
     "currencyname" : "Navy Chits", 
     "textcolor" : "#FFFFFF", 
     "bgcolor" : "#77AADD" 
    }, 
    "H" : 
    { 
     "JackID" : "1", 
     "Faction" : "H", 
     "Regard" : "-20", 
     "Currency" : "0", 
     "factionName" : "Hiver", 
     "factionKing" : "99", 
     "Tcurrency" : "0", 
     "currencyname" : "", 
     "textcolor" : "#000000", 
     "bgcolor" : "#CC9900" 
    } 
} 

我使用的是詹姆斯·牛頓 - 國王的Json.NET解析器和調用:

JackFactionList jackFactionList = JsonConvert.DeserializeObject<JackFactionList>(sJson); 

凡我類定義如下:

namespace Controller 
{ 
    public class JackFactionList 
    { 
     public JackFaction B; 
     public JackFaction P; 
     public JackFaction N; 
     public JackFaction H; 
    } 

    public class JackFaction 
    { 
     public int JackId { get; set; } 
     public string Faction { get; set; } 
     public int Regard {get; set;} 
     public int Currency {get; set;} 
     // Faction details 
     public string factionName {get; set;} 
     public string factionKing {get; set;} 
     public int Tcurrency {get; set;} 
     public string currencyname {get; set;} 
     public string textcolor {get; set;} 
     public string bgcolor {get; set;} 
    } 
} 

這一切都有效,但原始列表可能有不同的JackFactions而不是B,P,N和H. Ide盟友什麼,我想獲得的是:

public class JackFactionList 
{ 
    public List<JackFaction> factionList; 
} 

不改變JSON字符串,我怎樣才能得到JackFactions作爲一個列表,而不是單獨的對象?

回答

8

可以序列它作爲一個字典:

var jackFactionList = JsonConvert.DeserializeObject<Dictionary<string,JackFaction>>(sJson); 

然後你就可以得到的值:

List<JackFaction> result = jackFactionList.Values.ToList(); 
+0

我知道有人會知道答案。這工作完美。謝謝! – Dave