【.net core】Newtonsoft.Json.DeserializeObject反序列化类对象的坑

在使用Newtonsoft.Json.DeserializeObject反序列化成Class的时候,如果类中有数组,且41行构造函数没有其他参数的情况下,数组会将初始值与新的数组直接组合后返回,引起错误!

如果随便加的参数就没有问题。。。【待源码调试,后续补坑】

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using Newtonsoft.Json;
 5 class Program
 6 {
 7     static void Main(string[] args)
 8     {
 9         Student s1 = new Student();
10         String ss = "{\"Name\":\"hanzheng\",\"courses\":[\"m1\",\"m2\"],\"courses2\":[\"n1\",\"n2\"]}";
11         Student s2 = JsonConvert.DeserializeObject<Student>(ss);
12         Console.Write("123");
13     }
14 }
15 
16 public class Student
17 {
18     private string _name; // This is the so-called "backing field"
19     public string Name // This is your property
20     {
21         get {
22             return _name;
23         }
24         set {
25             _name = value;
26         }
27     }
28     public List<string> courses { get; set; }
29     private List<String> _courses2;
30     public List<string> courses2
31     {
32         get {
33             return _courses2;
34         }
35         set {
36             _courses2 = value;
37             _courses2.Distinct().ToList();
38         }
39     }
40 
41     public Student()
42     {
43 
44         mak();
45 
46 
47     }
48     private void mak()
49     {
50         Name = "m123";
51         courses = new List<string> { "h1", "h2" };
52         courses2 = new List<string> { "s1", "s2" };
53     }
54 }

 

上一篇:Newtonsoft提取多层嵌套的JSON


下一篇:Newtonsoft.Json Json工具的使用、类型方法大全