我的 C# Windows 应用程序使用 JavaScriptSerializer 从特定 URL 请求 JSON。
JSON 看起来像下面这样:
{"outcomes":[{"outcome_coef":2.8,"outcome_id":159370020,"outcome_name":"first","outcome_type_id":4,"outcome_visible":"yes","participant_number":1,"outcome_perc_stat":0.0},
{"outcome_coef":1.19,"outcome_id":159370022,"outcome_name":"second","outcome_type_id":5,"outcome_visible":"yes","participant_number":2,"outcome_perc_stat":0.0},
{"outcome_coef":1.01,"outcome_id":159370021,"outcome_name":"third","outcome_type_id":6,"outcome_visible":"yes","participant_number":3,"outcome_perc_stat":0.0}]}
比如我只需要得到outcome_coef和outcome_id。不需要数组的其余部分。
我正在尝试使用以下代码:
JavaScriptSerializer js = new JavaScriptSerializer();
var response = js.Deserialize<Response>(sr.ReadToEnd());
我的 Response 类如下所示:
public class Response
{
public Outcomes[] outcomes { get; set; }
}
public class Outcomes
{
public float outcome_coef { get; set; }
public int outcome_id { get; set; }
}
但它不起作用。
如何在不声明类中所有数组名称的情况下只解析 JSON 中需要的部分?
编辑:
有时 JSON 采用以下格式,在反序列化后它会给我 null 异常(它在开始或结束时带有额外的数组):
{"event_history":[],"outcomes":[{"outcome_coef":2.8,"outcome_id":159370020,"outcome_name":"first","outcome_type_id":4,"outcome_visible":"yes","participant_number":1,"outcome_perc_stat":0.0},
{"outcome_coef":1.19,"outcome_id":159370022,"outcome_name":"second","outcome_type_id":5,"outcome_visible":"yes","participant_number":2,"outcome_perc_stat":0.0},
{"outcome_coef":1.01,"outcome_id":159370021,"outcome_name":"third","outcome_type_id":6,"outcome_visible":"yes","participant_number":3,"outcome_perc_stat":0.0}], "event_stats":null}
在这种情况下,我是否也必须为其他数组创建变量?
请您参考如下方法:
这与 Json.NET 完美配合:
void Main()
{
var jsonString = File.ReadAllText(@"C:\text.json");
var json = JsonConvert.DeserializeObject<Response>(jsonString);
}
public class Response
{
public Outcomes[] outcomes { get; set; }
}
public class Outcomes
{
[JsonProperty("outcome_coef")]
public float OutcomeCoef { get; set; }
[JsonProperty("outcome_id")]
public int OutcomeId { get; set; }
}
