.net core - Json JObject JArray详解

NuGet中添加最新稳定版:

Newtonsoft.Json

  

新建类:

using System;

namespace SystemClass.JsonStudy
{
    class Person
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public DateTime Birthday { get; set; }

        public bool IsVIP { get; set; }

        public float Account { get; set; }

        public string[] Favorites { get; set; }

        public string Remark { get; set; }

        public static Person GetPerson()
        {
            Person person = new Person
            {
                ID = 1,
                Name = "张三",
                Birthday = DateTime.Now,
                IsVIP = true,
                Account = 12.34f,
                Favorites = new string[] { "起床", "上班" }
            };
            return person;
        }
    }
}

  

使用:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace SystemClass.JsonStudy
{
    class Program
    {
        static void Main(string[] args)
        {
            //0 创建一个 Person 实例
            Person entity = Person.GetPerson();
            string jsonStr = string.Empty;

            //1 实体类的 Json 序列化和反序列化
            //  1.1 Json 序列化
            //      1.1.1返回不缩进的 Json 字符串【见图01】
            jsonStr = JsonConvert.SerializeObject(entity);
            //      1.1.2返回缩进的 Json 字符串【见图02】
            jsonStr = JsonConvert.SerializeObject(entity, Formatting.Indented);

            //  1.2 将不缩进的 JSON 字符串转成缩进形式【见图03】
            jsonStr = JsonConvert.SerializeObject(entity);
            JObject jObject = JObject.Parse(jsonStr);
            jObject.ToString();

            //  1.3 其他设置【见图04】
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                DateFormatString = "yyyy-MM-dd HH:mm:ss",//设置日期格式
                NullValueHandling = NullValueHandling.Ignore,//忽略【null】值
                Formatting = Formatting.Indented//缩进
            };
            jsonStr = JsonConvert.SerializeObject(entity, settings);

            //  1.4 Json 反序列化【在不知道类的情况下,可以直接将json字符串转为JObject】
            var person = JsonConvert.DeserializeObject<Person>(jsonStr);


            //2 JObject 使用
            //  2.1 创建对象
            JObject obj = new JObject();
            obj.Add("ID", 1);
            obj.Add("Name", "张三");
            obj.Add("Birthday", DateTime.Parse("2000-01-02"));
            obj.Add("IsVIP", true);
            obj.Add("Account", 12.34f);
            //      创建数组
            JArray array = new JArray();
            array.Add(new JValue("吃饭"));
            array.Add(new JValue("睡觉"));
            obj.Add("Favorites", array);
            obj.Add("Remark", null);
            //      2.1.1 遍历 JObject 对象
            foreach (JProperty item in obj.Children())
            {
                Console.WriteLine("Name=" + item.Name + "-Value=" + item.Value);
            }

            //  2.2 JObject 中添加数组
            //      上例中的代码可以简化为:
            JArray array1 = new JArray("吃饭", "睡觉");

            //  2.3 从 Json 字符串创建 JObject
            string json = "{\"ID\":1,\"Name\":\"张三\",\"Birthday\":\"2000-01-02T00:00:00\",\"IsVIP\":true,\"Account\":12.34,\"Favorites\":[\"吃饭\",\"睡觉\"],\"Remark\":null}";
            JObject obj1 = JObject.Parse(json);
            Console.WriteLine(obj1.ToString());
            Console.WriteLine(AddStr(json, "add", "add"));

            //  2.4 从 Entity 创建 JObject
            JObject obj2 = JObject.FromObject(entity);

            //  2.5 用匿名对象创建 JObject
            JObject obj3 = JObject.FromObject(new { name = "jack", age = 18 });
            /*显示
            {
                "name": "jack",
                "age": 18
            }
            */

            //  2.6 用初始化器
            JObject obj5 = new JObject()
            {
                { "name" , "李四" },
                { "age", 29 }
            };

            //  2.7 获取值
            int id;
            if (obj1["ID"] != null)
            {
                id = obj["ID"].Value<int>();
            }
            JObject _jObject = JObject.Parse("{ID:{ID1:{ID2:'value',name:'valueName'}},'Name':'test','Mark':'Hello Word'}");
            var _value = _jObject["ID"]["ID1"]["ID2"].ToString();    //取值
        }

        /// <summary>添加一个属性
        /// C#给JSON对象添加一个键值对
        /// </summary>
        /// <param name="obj">待添加属性的对象</param>
        /// <param name="key">键名</param>
        /// <param name="value">值</param>
        /// <returns>添加属性后的对象</returns>
        public static object Add(object obj, string key, object value)
        {
            JObject jObj = JObject.Parse(JsonConvert.SerializeObject(obj));
            jObj.Add(new JProperty(key, value));
            return JsonConvert.DeserializeObject(jObj.ToString());
        }

        /// <summary>添加一个属性
        /// C#给JSON字符串添加一个键值对
        /// </summary>
        /// <param name="obj">待添加属性的对象</param>
        /// <param name="key">键名</param>
        /// <param name="value">值</param>
        /// <returns>添加属性后的对象</returns>
        public static object AddStr(string obj, string key, object value)
        {
            JObject jObj = JObject.Parse(obj);
            jObj.Add(new JProperty(key, value));
            return JsonConvert.DeserializeObject(jObj.ToString());
        }
    }
}

  

posted @ 2020-12-28 15:26  gygtech  Views(1500)  Comments(0Edit  收藏  举报