【发布时间】:2015-04-02 18:36:56
【问题描述】:
我正在尝试反序列化嵌套 Json,但它一直返回空值。
json:
{
"count":1,
"page":1,
"last_page":1,
"total":1,
"results":[
{
"data_id":24,
"name":"Sealed Package of Snowballs",
"rarity":1,
"restriction_level":0,
"img":"https:\/\/render.guildwars2.com\/file\/1D05D1EE04E16E69710E1EAB11AC466BBF105778\/219347.png",
"type_id":3,
"sub_type_id":2,
"price_last_changed":"2015-04-02 14:57:33 UTC",
"max_offer_unit_price":91,
"min_sale_unit_price":120,
"offer_availability":20969,
"sale_availability":18702,
"sale_price_change_last_hour":0,
"offer_price_change_last_hour":0
}
]
}
我可以毫无问题地反序列化 Count、page、last_page 和 total。但是嵌套低一级的所有内容都返回一个空值。
这是反序列化代码:
public Result GetApi(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<Result>(jsonReader);
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
这些是类:
public class Result
{
public int data_id { get; set; }
public string name { get; set; }
public int rarity { get; set; }
public int restriction_level { get; set; }
public string img { get; set; }
public int type_id { get; set; }
public int sub_type_id { get; set; }
public string price_last_changed { get; set; }
public int max_offer_unit_price { get; set; }
public int min_sale_unit_price { get; set; }
public int offer_availability { get; set; }
public int sale_availability { get; set; }
public int sale_price_change_last_hour { get; set; }
public int offer_price_change_last_hour { get; set; }
}
public class RootObject
{
public int count { get; set; }
public int page { get; set; }
public int last_page { get; set; }
public int total { get; set; }
public List<Result> results { get; set; }
}
为什么嵌套的 Json 返回 null 值?
【问题讨论】:
-
您不应该将其反序列化为
RootObject吗? -
在 RootObject 中我无法访问正确的属性,在 Result 中我可以。
-
你必须深入研究它:
data.results[0].name;查看类:一个 RootObject 包含一个数组/结果列表,其中 Name 是 -
@Plutonix 谢谢,这成功了,现在也明白为什么了。非常感谢,对不起我这个愚蠢的愚蠢错误..
标签: c# json serialization null nested