假设我想将所有这些数据都放入一个c#对象中,但"totalDamageTaken"除外,那么最好的方法是什么?
{
"modifyDate": 1414968686000,
"champions": [
{
"id": 76,
"stats": {
"totalDeathsPerSession": 294,
"totalSessionsPlayed": 44,
"totalDamageTaken": 1065678,
}
},
{
"id": 9,
"stats": {
"totalDeathsPerSession": 7,
"totalSessionsPlayed": 1,
"totalDamageTaken": 45382,
}
},
{
"id": 10,
"stats": {
"totalDeathsPerSession": 65,
"totalSessionsPlayed": 12,
"totalDamageTaken": 302252,
}
},
{
"id": 7,
"stats": {
"totalDeathsPerSession": 40,
"totalSessionsPlayed": 4,
"totalDamageTaken": 98114,
}
}
],
"summonerId": 24609204
}
我走的路对吗?
public class champion
{
public int id { get; set; }
public champion (int id)
{
this.id = id;
}
}
public class getStats
{
public int id { get; set; }
public long moddate { get; set; }
public static int length { get; set; }
public List<champion> champions;
public getStats(string json)
{
JObject jobject = JObject.Parse(json);
id = (int)jobject["summonerId"];
moddate = (long)jobject["modifyDate"];
}
}
我尝试过反序列化、selecttoken、jarrays和我见过的各种东西。
在将[JsonIgnore]
属性添加到totalDamageTaken
之后,使用JsonConvert.Deserialize(json);
进行反序列化。就这么简单。
如果不想使用外部库,可以在项目(.NET Framework的一部分)中包含对System.Runtime.Serialization的引用,并使用DataContractJsonSerializer(System.RuntimeSerialization.Json.DataContractJson序列化器)。
首先用[DataContract]属性装饰类,用[DataMember]属性装饰每个属性,如下所示。只包括您想要反序列化的属性(不要在stats类上包括totalDamageTaken属性)
[DataContract]
public class root
{
[DataMember]
public long modifyDate { get; set; }
[DataMember]
public int summonerId { get; set; }
[DataMember]
public IEnumerable<champion> champions { get; set; }
}
[DataContract]
public class champion
{
[DataMember]
public int id { get; set; }
[DataMember]
public stats stats { get; set; }
}
[DataContract]
public class stats
{
[DataMember]
public int totalDeathsPerSession { get; set; }
[DataMember]
public int totalSessionsPlayed { get; set; }
}
然后调用DataContractJsonSerializer
// From text
string text = // Json text as string
//// This is kind of a hack, however you do it it's easiest to work with a stream
byte[] chars = text.ToCharArray().Select(c => Convert.ToByte(c)).ToArray();
using (Stream stream = new MemoryStream(chars))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(root));
root result = (root)serializer.ReadObject(stream);
}
// From web request
HttpWebResponse request = // Get your request object back from a WebRequest object
using (Stream stream = request.GetResponseStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(root));
root result = (root)serializer.ReadObject(stream);
}