Json.NET 入门

Json.NET是 Json的.net框架实现,有了它我们可以在.NET程序中方便的使用 Json,例如:解析 Json 字符串的键值、生成 Json 字符串、与对象之间进行转换等等。而且是开源的,非常方便我们学习和使用。

Json.NET的网址:https://www.newtonsoft.com/json


下面介绍一些基本的使用方法

使用下面代码前,需先添加引用

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

1. 读取 Json 字符串中的键值信息

        static void Main(string[] args)
        {
            string jStr = "{name: 'momo', birthday: '2016-8-1', weidht: 11.5, loveFoods: ['milk', 'chicken']}"; //Json 字符串
            JObject jObj = null;
            try
            {
                jObj = JObject.Parse(jStr); //将 Json 字符串转换成 JObject 类型,如果 Json 字符串不合法,会异常。
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            //通过名称读取值
            Console.WriteLine("=========================通过名称读取值");
            Console.WriteLine(jObj["name"]);
            Console.WriteLine(jObj.GetValue("birthday"));
            //遍历所有键值对
            Console.WriteLine("=========================遍历所有键值对");
            foreach (var item in jObj)
            {
                Console.WriteLine(item.Key.ToString() + ": " + item.Value.ToString());
            }

            Console.ReadLine();
        }

输出结果

2. 生成 Json 字符串

       //生成 Json 字符串
            Console.WriteLine("=========================生成 Json 字符串");
            JObject jObj2 = new JObject();
            string name = "tongtong";
            int age = 2;
            JArray interests = new JArray("singing", "swim", "watching TV");
            jObj2.Add("name", name);
            jObj2.Add("age", age);
            jObj2.Add("interests", interests);
            Console.WriteLine(jObj2.ToString(Formatting.Indented));

输出结果

3. 对象和 Json 字符串互相转换

先定义一个类

    public class Person
    {
        public string Name { get; set; } = "momo";
        public DateTime Birthday { get; set; } = new DateTime(2016, 8, 1);
        public double Weight { get; set; } = 11.5;
        public string[] LoveFoods { get; set; } = new string[] { "milk", "chicken" };
    }

 使用 JsonConvert 中的方法进行转换

       //对象转化成 Json
            Console.WriteLine("=========================对象转化成 Json");
            Person person1 = new Person();
            person1.Name = "Lily";
            string jStr1 = JsonConvert.SerializeObject(person1, Formatting.Indented);
            Console.WriteLine(jStr1);
            //Json 转化成对象
            Console.WriteLine("=========================Json 转化成对象");
            Person person2 = JsonConvert.DeserializeObject<Person>(jStr1);
            Console.WriteLine(person2.Name);

输出结果

 总结

Json.Net 的功能远不止于此,查看帮助文档深入学习。

帮助文档地址:https://www.newtonsoft.com/json/help/html/Introduction.htm

注:这里程序测试使用的是 Json.net 2.0 的dll。

猜你喜欢

转载自www.cnblogs.com/JCYYF/p/9562404.html