ASP.NET API从MongoDB获取Cart对象时丢失Items子数组问题
问题解决:ASP.NET API从MongoDB获取Cart对象时缺失Items列表
问题原因分析
从代码和返回结果来看,核心问题出在实体类的成员访问权限与序列化配置上:
Carts类中的items字段默认是私有(private)访问级别,JSON序列化器只会处理公共(public)成员,导致该字段不会被序列化返回。CartItem类使用的[DataMember]是WCF序列化属性,对ASP.NET常用的JSON序列化器(System.Text.Json/Newtonsoft.Json)无效,可能影响子对象的序列化。
具体修复步骤
1. 修改Carts类的items字段为公共访问级别
将私有字段改为public,确保序列化器能识别并处理它:
public class Carts { [BsonId] public string Id { get; set; } public string buyer { get; set; } public double total { get; set; } [BsonElement("items")] // 改为public访问级别 public List<CartItem> items { get; set; } }
2. 替换CartItem的序列化属性(可选但推荐)
把[DataMember]替换为对应JSON序列化器的属性,确保子对象能正确序列化:
- 若使用System.Text.Json(ASP.NET Core默认):
public class CartItem { [JsonPropertyName("name")] public string name { get; set; } [JsonPropertyName("amount")] public int amount { get; set; } [JsonPropertyName("price")] public double price { get; set; } }
- 若使用Newtonsoft.Json:
public class CartItem { [JsonProperty("name")] public string name { get; set; } [JsonProperty("amount")] public int amount { get; set; } [JsonProperty("price")] public double price { get; set; } }
3. 确保MongoDB数据类型匹配(可选)
注意MongoDB中total、amount、price存储的是字符串类型,但实体类用的是数值类型,可添加[BsonRepresentation(BsonType.String)]属性确保转换正常:
public class Carts { [BsonId] public string Id { get; set; } public string buyer { get; set; } [BsonRepresentation(BsonType.String)] public double total { get; set; } [BsonElement("items")] public List<CartItem> items { get; set; } } public class CartItem { [JsonPropertyName("name")] public string name { get; set; } [BsonRepresentation(BsonType.String)] [JsonPropertyName("amount")] public int amount { get; set; } [BsonRepresentation(BsonType.String)] [JsonPropertyName("price")] public double price { get; set; } }
验证修改效果
重新运行API,调用获取Cart列表的接口,返回结果会包含完整的items数组:
[{"id":"temp","buyer":"test","total":2300000,"items":[{"name":"IP-8","amount":2,"price":20000},{"name":"IP-12","amount":2,"price":20000}]}]
内容的提问来源于stack exchange,提问作者Gia Bảo
相关产品推荐
相关产品推荐

