NewtonJson 的一个例子

person 类 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewTonJSONTest
{
    class Person
    {
    public string Name { get; set; }
    public int Age { get; set; }
     public string[] Mobiles { get; set; }
    }
}

一个控制台程序的默认的类,也是main所在的类 Program 代码如下:

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

namespace NewTonJSONTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            List<Person> person0;
            List<Person> person = new List<Person>(){
               new Person() {Name = "China Mobile", Age = 30, Mobiles = new string[] {"13800138000","10086"}},
               new Person() {Name = "China Telecom", Age = 60, Mobiles = new string[] {"10000","189"}},
               new Person() {Name = "China Unicom", Age = 90, Mobiles = new string[] {"10010"}}
            };
            // 序列化为JSON字串
            string str_json = JsonConvert.SerializeObject(person);
            Console.WriteLine(str_json);
            Console.WriteLine("序列化完成了,序列化了对象为一个json字符串");


            // 反序列化为Person列表对象 ,反序列化是☞str_json字符串 序列化为一个对象
            person0 = JsonConvert.DeserializeObject<List<Person>>(str_json);
            foreach (var temp in person0)
            {
                Console.WriteLine(temp.Age + " " + temp.Name + " " + temp.Mobiles + "\n");
            }

            //  JObject oPostData = JsonConvert.DeserializeObject<JObject>(str_json); //@@

            //  oPostData.GetValue("Channel").ToString();//@@
        }
    }
}

运行结果 如下图:

Hello World!
[{"Name":"China Mobile","Age":30,"Mobiles":["13800138000","10086"]},{"Name":"China Telecom","Age":60,"Mobiles":["10000","189"]},{"Name":"China Unicom","Age":90,"Mobiles":["10010"]}]
序列化完成了,序列化了对象为一个json字符串
30 China Mobile System.String[]

60 China Telecom System.String[]

90 China Unicom System.String[]


D:\Users\86133\source\repos\NewTonJSONTest\NewTonJSONTest\bin\Debug\net5.0\NewTonJSONTest.exe (进程 28896)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值