Combobox is loading wrong array information

0

I made a C # (WinForms) application to load the marks according to the type of vehicle that is selected (car, motorcycle or truck) in a combobox. I put the following code at a button:

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 clicking will load the 'Brand' combobox. What happens is that when I click on load the combobox is populated with the information (Collection) repeatedly, as shown below.

Maybe I'm missing some information from the array, but I honestly do not know what to do in this case. If it was not very clear, let me know what I'm trying to say in the comments.

Thanks

    
asked by anonymous 13.04.2016 / 16:47

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, since each Combo item is an array.

By analyzing the JSON of this API, you can 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 marca property in the combo for selection, then your code might 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);

However I suggest instead of using JavascriptSerializer, use JSON.NET ( link ) which is much faster and more complete. With it you can deserialize JSON to an anonymous object, something like this:

var model = JsonConvert.DeserializeAnonymousType(json, new[] {
    new {
        fipe_marca = "",
        name = "",
        marca = "",
        key = "",
        id = "",
        fipe_name = ""
}});
    
13.04.2016 / 17:37