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。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
|