将选中的列表框选中的项添加到JSON
本文关键字:JSON 添加 列表 | 更新日期: 2023-09-27 18:27:18
好吧,我这里有一个选中的列表框,我想把选中的项添加到我的列表中,然后用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"
有人能帮我一把吗?如果我能学会这一点,我将不胜感激!提前感谢大家!
我认为您不会得到这样的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"}]}]
*注意,我只是在脑子里打出来的,可能会有一些错误,但希望它能给你指明正确的方向。