mardi 21 avril 2015

Deserialize and parse only needed arrays from JSON Array

My C# Windows Application uses JavaScriptSerializer to request JSON from certain URL.

JSON looks something like below:

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

For example, I only need to get outcome_coef and outcome_id. The rest of the array is not needed.

I am trying to use the following code:

JavaScriptSerializer js = new JavaScriptSerializer();
var response = js.Deserialize<Response>(sr.ReadToEnd());

My Response class looks like this:

public class Response
{
    public Outcomes[] outcomes { get; set; }
}

public class Outcomes
{
    public float outcome_coef { get; set; }
    public int outcome_id { get; set; }
}

But it is not working.

How can I parse only needed part out of JSON without declaring all the array names inside my class?

Aucun commentaire:

Enregistrer un commentaire