亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JSON.net 用 int 的嵌套列表序列化對象

JSON.net 用 int 的嵌套列表序列化對象

C#
慕容708150 2022-06-12 10:48:46
我遇到了以下問題,希望您能幫助我:使用 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();


查看完整回答
反對 回復 2022-06-12
  • 1 回答
  • 0 關注
  • 189 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號