从JSON Array反序列化和解析所需的数组

时间:2015-04-21 10:52:28

标签: c# json winforms

我的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_coefoutcome_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 Exception(它在开头或结尾附带了额外的数组):

{"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}

在这种情况下,我是否还必须为其他数组创建变量?

2 个答案:

答案 0 :(得分:2)

如果您使用JSON.Net,则根本不需要模型:

dynamic result = JsonConvert.Deserialize(jsonString);
var myArray = result.outcomes[1]; // get array at index 1
Console.WriteLine(myArray.outcome_coef); // output: 1.19

答案 1 :(得分:2)

这适用于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; }
}