标签:mes image width closed col bug http void 搜索
准备工作
一、新建控制台程序用于测试
二、管理NuGet程序包——搜索<Newtonsoft.json> —— 安装所需程序包
三、引用 using Newtonsoft.Json
开始测试
创建所用的类
添加数据
序列化数据——JsonConvert.SerializeObject(Object);
DeBug查看:
打看Json可视化工具查看:
控制台输出结果:
反序列化
单条数据: object 参数 = JsonConvert.DeserializeObject<object>(json);
多条数据:List<object> 参数 = JsonConvert.DeserializeObject<List<object>>(json);
结果:
1 using Newtonsoft.Json; 2 using System; 3 using System.Collections.Generic; 4 5 namespace Json_Demo 6 { 7 public class Program 8 { 9 static void Main(string[] args) 10 { 11 //添加数据 12 List<Student> students = new List<Student> 13 { 14 new Student { ID = 1, Name = "test1", Age = 20, Gender= Gender.男, Grade = Grade.电子商务, Score = new Score { CShare = 91, Java = 89 , English = 80, Network = 70 } }, 15 new Student { ID = 2, Name = "test2", Age = 19, Gender= Gender.女, Grade = Grade.网络技术, Score = new Score { CShare = 84, Java = 77 , English = 94, Network = 86 } }, 16 new Student { ID = 3, Name = "test3", Age = 22, Gender= Gender.男, Grade = Grade.软件工程, Score = new Score { CShare = 88, Java = 96 , English = 93, Network = 90 } } 17 }; 18 19 Console.WriteLine("输入原数据:"); 20 foreach (var item in students) 21 { 22 Console.WriteLine(item.ID + "\t" + item.Name + "\t" + item.Age + "\t" + item.Gender + "\t" + 23 item.Score.CShare + "\t" + item.Score.Java + "\t" + item.Score.English + "\t" + item.Score.Network); 24 } 25 26 Console.WriteLine("序列化数据:"); 27 var jsonStr = JsonConvert.SerializeObject(students); 28 29 Console.WriteLine(jsonStr); 30 31 Console.WriteLine("反序列化数据:"); 32 33 List<Student> jsonToObject = JsonConvert.DeserializeObject<List<Student>>(jsonStr); 34 35 foreach (var item in jsonToObject) 36 { 37 Console.WriteLine(item.ID + "\t" + item.Name + "\t" + item.Age + "\t" + item.Gender + "\t" + 38 item.Score.CShare + "\t" + item.Score.Java + "\t" + item.Score.English + "\t" + item.Score.Network); 39 } 40 41 Console.ReadKey(); 42 } 43 } 44 45 46 /// <summary> 47 /// 性别 48 /// </summary> 49 public enum Gender 50 { 51 男, 52 女 53 } 54 55 /// <summary> 56 /// 班级 57 /// </summary> 58 public enum Grade 59 { 60 软件工程, 61 网络技术, 62 电子商务 63 } 64 65 /// <summary> 66 /// 分数 67 /// </summary> 68 public class Score 69 { 70 public int CShare { get; set; } 71 72 public int Java { get; set; } 73 74 public int English { get; set; } 75 76 public int Network { get; set; } 77 78 } 79 80 /// <summary> 81 /// 学生类 82 /// </summary> 83 public class Student 84 { 85 public int ID { get; set; } 86 87 public string Name { get; set; } 88 89 public int Age { get; set; } 90 91 public Gender Gender { get; set; } 92 93 public Grade Grade { get; set; } 94 95 public Score Score { get; set; } 96 } 97 }
写作与思考共存!
标签:mes image width closed col bug http void 搜索
原文地址:https://www.cnblogs.com/junweiTang/p/11142264.html