我遇到了以下問題,希望您能幫助我:使用 JSON.net 對ProductModel具有許多屬性和屬性的域模型進行序列化/反序列化,包括公共和私有JsonProperty屬性,并用于對屬性進行序列化/反序列化,并JsonIgnore避免來自屬性的重復(用作屬性的包裝器)。一些屬性是通用嵌套ICollection的(類型int和其他模型)并且不使用JsonIgnore屬性。當應用程序接收到 JSON 時,它會正確反序列化,但是當需要對對象模型進行序列化時,只有那些ICollection沒有int正確序列化,就像一個空的 JSON 數組一樣。public class ProductModel : ModelBase{ public ProductModel() { Product_stores = new List<int>(); Product_related = new List<int>(); Product_categories = new List<int>(); Product_discounts = new BindingList<ProductDiscountModel>(); } [JsonProperty("model")] private string model; [JsonProperty("location")] private string location; [JsonProperty("quantity")] private int quantity; [JsonProperty("product_category")] public ICollection<int> Product_categories { get; } // Not serilized but deserilized [JsonProperty("product_store")] public ICollection<int> Product_stores { get; } // Noy serilized but deserilized [JsonProperty("product_related")] public ICollection<int> Product_related { get; } // Not serilized but deserilized [JsonProperty("product_discount")] public ICollection<ProductDiscountModel> Product_discounts { get; } // Serilized/Deserilized correctly [JsonProperty("product_id")] public new int ID { get => base.ID; set => base.ID = value; } [JsonIgnore] public string Model { get => model; set { if (model == value) return; model = value; OnPropertyChanged(nameof(model)); } } [JsonIgnore] public string Location { get => location; set { if (location == value) return; location = value; OnPropertyChanged(nameof(location)); } }
1 回答

慕桂英4014372
TA貢獻1871條經驗 獲得超13個贊
如果您使用 JsonConvert.SerializeObject() 并確保整數列表在運行時正確填充項目,那么它肯定會將 ICollection 列表序列化為等效的 JSON 數組。在控制臺應用程序中嘗試以下代碼:
public ProductModel()
{
Product_stores = new List<int>();
Product_related = new List<int>();
Product_categories = new List<int>() { 1, 2 , 3 , 4};
}
var jsonStr = JsonConvert.SerializeObject(new ProductModel() , Formatting.Indented);
Console.WriteLine(jsonStr);
Console.ReadLine();
- 1 回答
- 0 關注
- 189 瀏覽
添加回答
舉報
0/150
提交
取消