求助:使用Console.WriteLine(JsonSerializer.Serialize)返回空JSON对象
问题:使用JsonSerializer.Serialize输出对象时仅得到空JSON {}
你遇到的问题是因为System.Text.Json默认只序列化公共属性(Properties),而你的DogLeash和Product类里定义的都是公共字段(Fields,没有get/set访问器的成员),这些字段会被序列化器忽略,所以最终输出空对象{}。
解决方案
有两种可行的解决方式,任选其一即可:
方案1:将字段改为属性(推荐)
这是符合C#封装规范的做法,修改类定义,把字段改成带get/set访问器的属性:
修改Product.cs:
namespace PetShopPart1 { public class Product { public string Name { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } = 0; public string Description { get; set; } } }
修改DogLeash.cs:
namespace PetShopPart1 { class DogLeash : Product { public int LengthInches { get; set; } public string Material { get; set; } } }
方案2:配置序列化选项包含字段
如果不想修改类结构,可以在序列化时传入JsonSerializerOptions,指定序列化器包含公共字段:
首先确保Program.cs顶部引用了命名空间:
using System.Text.Json;
然后修改序列化的代码:
var serializeOptions = new JsonSerializerOptions { IncludeFields = true }; Console.WriteLine(JsonSerializer.Serialize(dogLeash, serializeOptions));
验证效果
修改完成后,当你输入数据触发序列化时,就能得到包含所有成员值的JSON输出,示例如下:
{"Name":null,"Price":0,"Quantity":2,"Description":null,"LengthInches":48,"Material":"Nylon"}
内容的提问来源于stack exchange,提问作者Aaron Sierp
相关产品推荐
相关产品推荐

