How to insert values inside a key using List and JSON

0

I'm trying to do something that gives me output like this:

[
    {
        "Nome": "João",
        "Comprou": [
                       "Carro": "Sedan", "Preco": "12000",
                       "Moto": "Honda", "Preco": "8000"
                   ]
    }
]

For this I use List and to save JSON.net usage. The problem is that I can not put a key inside another. I tried this way:

public class Cliente
{
    public string Nome { get; set; }
    public string[] Comprou { get; set; }
}
public static List<Cliente> Clientes = new List<Cliente>();

I do not know how to assign one value within another. I want to get the products and put them in a listbox for the particular client that is selected in another listbox. I tried using foreach:

Cliente cliente = Clientes[listaClientes.SelectedIndex];
foreach (var produto in cliente.Comprou)
{
        listaProdutosComprados.Items.Add(produto);
}

I wanted to put the values as "Name" and "Price" just like I did with the client so that I can then display these values in a label or textbox. I'm developing this project in C # with a WinForms application.

    
asked by anonymous 30.10.2014 / 21:04

1 answer

3

You need to expand your JSON.Net template a bit more by doing the right interpretation:

public class Cliente
{
    public string Nome { get; set; }
    public List<Veiculo> Comprou { get; set; }
}

public class Veiculo
{
    public string Carro { get; set; }  
    public string Moto { get; set; }
    public Decimal Preco { get; set; }
}

You can instantiate like this:

var clientes = new List<Cliente> {
    Nome = "João", 
    Comprou = new List<Veiculo> {
        new Veiculo {
            Carro = "Sedan",
            Preco = 12000
        },
        new Veiculo {
            Moto = "Honda",
            Preco = 8000
        }
    }
};

To serialize in JSON:

string output = JsonConvert.SerializeObject(clientes);

Source: link

    
30.10.2014 / 21:33