在另一个列表中添加一个列表并使用JSON.net进行序列化

时间:2014-11-01 03:13:43

标签: c# .net json winforms

我会尝试尽可能具体。
我有一个注册客户的系统。通过注册客户,它将添加到我的列表和我的客户列表框中,其中包含以下代码:

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

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

private void btnRegisterCustomer_Click(object sender, EventArgs e)
{
    Customer customer = new Customer();
    customer.CustomerNumber = textboxNumber.Text;
    customer.Name = textboxName.Text;
    customersList.Items.Add(customer.Name);
    Customers.Add(customer);
}

要保存以存档我使用的客户数据:

File.WriteAllText(customersFILE, JsonConvert.SerializeObject(Customers, Formatting.Indented));

这很有效。现在我将解释我的问题 我试图在列表框中向选定的客户注册产品。我的产品注册系统与客户相同。我需要将产品列表框中的所选产品添加到选定的客户。我在JSON输出中需要这样的东西:

[
    {
      "CustomerNumber": "001",
      "Name": "Jack",
      "Bought": [
                    {
                         "ProductName": "Boat", "ProductPrice": "20000", //I don't know if sintax is correct
                         "ProductName": "Car", "ProductPrice": "23000"
                    }
                ]
    }
]

我想要的是基本上将列表框中的所选产品添加到在另一个列表框中选择的所选客户。我通过这种方式尝试了一些事情:

public class Customer
{
    public string CustomerNumber { get; set; }
    public string Name { get; set; }
    public List<PurchasedProduct> Bought { get; set; }
}

public class PurchasedProduct
{
    public string ProductName { get; set; }
    public string ProductPrice { get; set; }
}

public static List<PurchasedProduct> PurchasedProducts = new List<PurchasedProduct>();

private void btnRegisterProductToCustomer_Click(object sender, EventArgs e)
{
    PurchasedProduct purchased = PurchasedProducts[customersListBox.SelectedIndex];
    purchased.ProductName = productNameTextBox.Text;
    purchased.ProductPrice = productPriceTextBox.Text;
    PurchasedProducts.Add(purchased);
    foreach (var product in purchased.ProductName)
        {
            purchasedProductsListBox.Items.Add(purchased);
        }
}

这不起作用。
我有这个来显示所选的客户信息:

private void customersListBoxSelectedIndexChanged(object sender, EventArgs e)
{
    Customer customer = Customers[customersListBox.SelectedIndex];
    labelCustomerNumber.Text = customer.CustomerNumber;
    labelCustomerName.Text = customer.Name;
    //I need now to display the info about the selected purchased product
    purchasedProductsListBox.Items.Clear();
    if (customer.Bought != null)
    {
        foreach (var productB in customer.Bought[customersListBox.SelectedIndex].Name)
        {
            purchasedProductsListBox.Items.Add(productB);
        }
    }
}

我需要获取客户选择的购买产品值,然后将其显示在客户值等标签中,但首先我必须弄清楚如何将产品数据存储在List中并使用JSON进行序列化。

0 个答案:

没有答案