为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 236 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号