c# - 将选中的列表框选中的项添加到JSON

时间:2014-10-20 23:05:22

标签: c# .net json winforms

好吧,我在这里有一个选中的列表框,我想将选中的项目添加到我的列表中,然后用JSON序列化它们。
例如:

public class Customer
{
     public string Name { get; set; }
     public string Products { get; set; }
}

List<Customer> Customers = new List<Customer>();

private void btnRegister_Click(object sender, EventArgs e)
{
    if(boxName.Text.Length != 0 && productsList.CheckedItems.Count != 0)
    {
        Customer customer = new Customer();
        customer.Name = boxName.Text;
        //This is what I tried
        foreach(var item in productsList.CheckedItems)
        {
            customer.Products = item.ToString();
        }
        Customers.Add(customer);
        customersList.Items.Add(customer.Name);
    }
}

//In one event I have this to save to the JSON file
File.WriteAllText(file, JsonConvert.SerializeObject(Customers));

但是我在JSON文件和客户列表中的输出只是一个选定产品的名称。如何得到所有并做这样的事情:

[{"Name":"Mathew", "Products":"car", "boat", "bike"}] //These products will be inserted according to the checked products in the checked listbox

如何为产品添加这些值?我也试图像这样定价:

"Products": "car": "Price":"20000", "boat": "Price":"30000", "bike":"Price":"2000"
有人可以帮我一个忙吗?如果我学到这一点,我将非常感激!提前谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你不会像这样得到Json,因为它似乎没有正确格式化。看看http://amundsen.com/media-types/collection/examples/

要获得类似于以下内容的东西,需要做类似以下的事情

public class ProductDetails
{
     public string ProdName { get; set; }
     public string Price { get; set; }
}    

public class Customer
{
     public string Name { get; set; }
     public List<ProductDetails> Products { get; set; }
}

List<Customer> Customers = new List<Customer>();

private void btnRegister_Click(object sender, EventArgs e)
{
    if(boxName.Text.Length != 0 && productsList.CheckedItems.Count != 0)
    {
        Customer customer = new Customer();
        customer.Name = boxName.Text;
        customer.Products = new List<ProductDetails>();

        //This is what I tried

        foreach(var item in productsList.CheckedItems)
        {
            ProductDetails details = new ProductDetails()
            details.ProdName = item,ToString();
            details.Price=  5;

            customer.Products.Add(details);
        }
        Customers.Add(customer);
        customersList.Items.Add(customer.Name);
    }
}

这应该会给你一个类似下面的输出

[{"Name":"Mathew", "Products": [{ "ProdName" : "car", "Price": "1000"}, {"ProdName":"boat", "Price": "10"}, {"ProdName": "bike", "Price" : "5"}]}]

*请注意我只是在脑海中输入了这个,可能会有一些错误,但希望它能指出正确的方向。