Newtonsoft.Json 用法

Newtonsoft.Json 用法

NuGet安装Newtonsoft.Json

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace test
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTran_Click(object sender, EventArgs e)
        {
            string json = @"{
                          'usercode': '9001',
                          'username': 'jiangzhihao',
                          'role': [
                            'user',
                            'admin'
                          ]
                        }";

            JObject jRole = (JObject)JsonConvert.DeserializeObject(json);

            string usercode = jRole["usercode"].ToString();
            tbLogLine.AppendText("usercode:" + usercode + Environment.NewLine);

            var result = jRole["role"].ToString();

            var arrRole = JArray.Parse(result);

            foreach (var jObject in arrRole)
            {
                //Console.WriteLine(jObject);
                tbLogLine.AppendText("role:" + jObject.ToString() + Environment.NewLine);

            }

            JObject obj = new JObject();
            obj.Add("billno", "SK2023020100001");
            obj.Add("itemno", "1");
            tbLogLine.AppendText(obj.ToString());
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。