List to JSON with JsonSerializer.Serializer 返回 null
Posted
技术标签:
【中文标题】List to JSON with JsonSerializer.Serializer 返回 null【英文标题】:List to JSON with JsonSerializer.Serializer returns null 【发布时间】:2021-08-05 19:15:09 【问题描述】:我有一个名为clsTest
的类,其定义为:
public class clsTest
public string Name;
public string Family;
public int Age;
我有另一个名为clsMain
的类,它将clsTest
类的三个实例序列化为JSON:
public class clsMain
public string mtdMain()
clsTest ct1_a = new clsTest();
clsTest ct1_b = new clsTest();
clsTest ct1_c = new clsTest();
ct1_a.Name = "Satoshi";
ct1_a.Family = "Nakamato";
ct1_b.Name = "Charles";
ct1_b.Family = "Hoskinson";
ct1_b.Age = 33;
ct1_c.Name = "AmirAli";
ct1_c.Family = "Sam";
ct1_c.Age = 25;
List<clsTest> lst = new List<clsTest>();
lst.Add(ct1_a);
lst.Add(ct1_b);
lst.Add(ct1_c);
JsonSerializerOptions option = new JsonSerializerOptions();
option.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
option.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
return JsonSerializer.Serialize(lst, option);
当我调试项目时,我的列表已满,如屏幕截图所示:
但最后return JsonSerializer.Serialize(lst, option);
序列化如下:
我找不到问题,任何建议将不胜感激。 谢谢。
【问题讨论】:
【参考方案1】:使用属性而不是字段,如下所示:
public class Test
public string Name get; set;
public string Family get; set;
public int Age get; set;
【讨论】:
以上是关于List to JSON with JsonSerializer.Serializer 返回 null的主要内容,如果未能解决你的问题,请参考以下文章
json comile sass to css with autoprefixer and webpack
[React] Refactor a Stateful List Component to a Functional Component with React PowerPlug
Java.util.Map to JSON Object with Jersey / JAXB / Jackson
Typescript JSON to Class with "es5"