2021-04-26json文本用c#进行读写,写的具体格式

json文本用c#进行读写,写的具体格式

首先:using Newtonsoft.Json;
对于newtonsoft.json可搜索如何下载

界面设计如下:

 this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.richTextBoxReadJson = new System.Windows.Forms.RichTextBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(108, 136);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(108, 209);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 1;
            this.button2.Text = "button2";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // richTextBoxReadJson
            // 
            this.richTextBoxReadJson.Location = new System.Drawing.Point(241, 101);
            this.richTextBoxReadJson.Name = "richTextBoxReadJson";
            this.richTextBoxReadJson.Size = new System.Drawing.Size(474, 195);
            this.richTextBoxReadJson.TabIndex = 2;
            this.richTextBoxReadJson.Text = "";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Controls.Add(this.richTextBoxReadJson);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

在这里插入图片描述

private readonly string _path = $"../../imitate.json";

		public Form1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)//read
		{
			try
			{
				string jsonFromFile;
				using (var reader = new StreamReader(_path))
				{
					jsonFromFile = reader.ReadToEnd();
				}

				richTextBoxReadJson.Text = jsonFromFile;

				var customerFromJson = JsonConvert.DeserializeObject<Customer>(jsonFromFile);
			}
			catch (Exception ex)
			{
				// ignored
			}
		}

		private void button2_Click(object sender, EventArgs e)//write
		{
			try
			{
				var customer = GetCustomer();

				var jsonToWrite = JsonConvert.SerializeObject(customer, Formatting.Indented);

				using (var writer = new StreamWriter(_path))
				{
					writer.Write(jsonToWrite);
				}
			}
			catch (Exception ex)
			{
				// ignored
			}
		}
		private Customer GetCustomer()
		{
			var customer = new Customer
			{
				Id = 1,
                Location = new Location
                {
                    City = "Vancouver",
                    Province = "BC"
                },
                Array1s = new List<int>
                {
					1,2,3
                },
                Orders = new List<Order>
                {
                    new Order
                    {
                        quantity=3,
                        Items = new List<Item>
                        {
                            new Item
                            {
                                Product = new Product
                                {
                                    Sku = "14u",
                                    Name = "hot",
                                },
                                WuLiao=new List<int>
                                {
									4,5,6
                                },
                            }
                        }
                    },
					new Order
					{
						quantity=3,
						Items = new List<Item>
						{
							new Item
							{
								Product = new Product
								{
									Sku = "14u",
									Name = "hot",
								},
								WuLiao=new List<int>
								{
									4,5,6
								},
							}
						}
					},
				}
            };

            return customer;
		}
	}

	public class Customer
	{
		public int Id { get; set; }
		public Location Location { get; set; }
		public List<int> Array1s { get; set; }
		public List<Order> Orders { get; set; }
	}

	public class Location
	{
		public string City { get; set; }
		public string Province { get; set; }
	}
	
	public class Order
	{
		public int quantity { get; set; }
		public List<Item> Items { get; set; }
	}

	public class Item
	{
		public Product Product { get; set; }
		public List<int> WuLiao { get; set; }
	}

	public class Product
	{
		public string Sku { get; set; }
		public string Name { get; set; }
	}

生成的json文件如下图:

{
  "Id": 1,
  "Location": {
    "City": "Vancouver",
    "Province": "BC"
  },
  "Array1s": [
    1,
    2,
    3
  ],
  "Orders": [
    {
      "quantity": 3,
      "Items": [
        {
          "Product": {
            "Sku": "14u",
            "Name": "hot"
          },
          "WuLiao": [
            4,
            5,
            6
          ]
        }
      ]
    },
    {
      "quantity": 3,
      "Items": [
        {
          "Product": {
            "Sku": "14u",
            "Name": "hot"
          },
          "WuLiao": [
            4,
            5,
            6
          ]
        }
      ]
    }
  ]
}

这里的参考文档是:
https://github.com/razorcx/json-example/blob/master/JsonExample/JsonExampleForm.cs

这部分代码实现了对json文件的读写。

着重展示了,json数组,json自定义类,json的元素赋值,数组元素的多层结构。2个易错点:
数组的赋值:

Array1s = new List<int>
                {
					1,2,3
                },
public List<int> Array1s { get; set; }

多层元素的赋值:

 Orders = new List<Order>
                {
                    new Order
                    {

public List<Order> Orders { get; set; }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值