当对象数量未知时反序列化Json
Posted
技术标签:
【中文标题】当对象数量未知时反序列化Json【英文标题】:Deserialize Json when number of objects is unknown 【发布时间】:2014-03-27 12:17:04 【问题描述】:我有一个 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"
我正在使用 James Newton-King 的 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。理想情况下,我想得到的是:
public class JackFactionList
public List<JackFaction> factionList;
在不更改 Json 字符串的情况下,如何将 JackFactions 作为列表而不是单个对象获取?
【问题讨论】:
【参考方案1】:您可以将其序列化为字典:
var jackFactionList = JsonConvert.DeserializeObject<Dictionary<string,JackFaction>>(sJson);
然后你可以得到值:
List<JackFaction> result = jackFactionList.Values.ToList();
【讨论】:
我知道有人会知道答案。这完美地工作。谢谢!以上是关于当对象数量未知时反序列化Json的主要内容,如果未能解决你的问题,请参考以下文章