Combobox loading wrong array information

Asked

Viewed 105 times

0

I made an application in C#(Winforms) to load the marks according to the type of vehicle that is selected (car, bike or walking)in a combobox. I put in a button the following code:

private void btnCheck_Click_1(object sender, EventArgs e)
        {
            Object tipoVeic = cmbTipo.SelectedItem;
            WebClient client = new WebClient();
            var url = "http://fipeapi.appspot.com/api/1/" + tipoVeic.ToString() + "/veiculos/21.json";
            var json = client.DownloadString(url);
            var serializar = new JavaScriptSerializer();

            var model = serializar.Deserialize<dynamic>(json);

            lblTipo.Text = tipoVeic.ToString();
            lblTipo.Visible = true;
            cmbMarca.Items.AddRange(model);
        }

When click will load the combobox 'Tag'. What happens is that when I click on load the combobox is filled with information (Collection) repeatedly, as shown below.

Combobox preenchido com a informação (Coleção)

Maybe I’m missing some information from the array, but I honestly don’t know what to do in this case. If it is not very clear, let me know that I try to specify better in the comments.

Thanks

1 answer

2


The problem is that you are deserializing the return JSON as a collection of anonymous objects and the Combobox control does not know which property to display, as each Combo item is an array.

By analyzing the JSON of this API, it is possible to map the return to a class like this:

public class Marca
{
    public string fipe_marca { get; set; }

    public string marca { get; set; }

    public string key { get; set; }

    public string id { get; set; }

    public string fipe_name { get; set; }
}

Assuming you want to display the property marca in the combo for selection, so your code can look like this:

var json = client.DownloadString(url);
var serializar = new JavaScriptSerializer();

var model = serializar.Deserialize<Marca[]>(json);

comboBox1.DisplayMember = "marca";
comboBox1.Items.AddRange(model);

But I suggest instead of using Javascriptserializer, using JSON.NET (http://www.newtonsoft.com/json) which is much faster and complete. With it you can deserialize JSON to an anonymous object, more or less like this:

var model = JsonConvert.DeserializeAnonymousType(json, new[] {
    new {
        fipe_marca = "",
        name = "",
        marca = "",
        key = "",
        id = "",
        fipe_name = ""
}});
  • worked dude, I used JSON.NET as you passed me, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.