【问题标题】:c# - Add checked listbox checked items to JSONc# - 将选中的列表框选中项添加到 JSON
【发布时间】:2014-10-21 09:18:59
【问题描述】:

好吧,我在这里有一个选中的列表框,我想将选中的项目添加到我的列表中,然后使用 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"

有人可以帮帮我吗?如果我能学到这一点,我将不胜感激!提前谢谢大家!

【问题讨论】:

  • 您在 foreach 循环中覆盖产品,连接字符串,如 customer.Products += item.ToString();以防止覆盖。
  • @Xela 这行得通,但是如何获得逗号分隔的产品?如果我必须定价,我将如何进行?比如“产品”:“汽车”:“价格”:“20000”,“船”:“价格”:“30000”,“自行车”:“价格”:“2000”

标签: c# .net json winforms


【解决方案1】:

我不认为你会得到这样的 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"}]}]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    相关资源
    最近更新 更多