所以,让我们说我想把所有这些数据都带到一个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和我见过的各种东西。
答案 0 :(得分:1)
将JsonConvert.Deserialize(json);
属性添加到[JsonIgnore]
后,使用totalDamageTaken
进行反序列化。它很简单。
答案 1 :(得分:0)
Json.NET是一个很好的选择,就像Jeroen Vannevel提到的那样,它比.NET框架的JSON反序列化器更宽容。
如果您不想使用外部库,可以在项目中包含对System.Runtime.Serialization的引用(.NET Framework的一部分)并使用DataContractJsonSerializer(System.Runtime.Serialization.Json) .DataContractJsonSerializer)。
首先使用[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);
}