【发布时间】:2019-07-24 07:30:38
【问题描述】:
我正在尝试反序列化 json,但无法得到我想要的。我想将 json 反序列化为 C# 对象,但我无法反序列化它的子对象。我想分享我的代码并征求您的意见...
{
"accessToken":"123",
"requestId":"5mRIo6Y6epripoBA3YTM+ZDVgDVR2adB43euMJETguSboG0HT6j7Uje5mU0je5CF",
"CreatedDate":"2019-07-24",
"CartDetail":{
"ProductId":"1",
"Qty":"2",
"Price":"3",
"CreatedDate":"2019-07-24"
}
}
这是尝试反序列化的 C# 代码
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
Cart cart = JsonConvert.DeserializeObject<Cart>(jsonContent);
此代码可以反序列化内部对象 CartDetail。我怎样才能解决这个问题?
这是购物车类
public partial class Cart
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Cart()
{
this.CartDetails = new HashSet<CartDetail>();
}
public int Id { get; set; }
public string RequestId { get; set; }
public string AccessToken { get; set; }
public Nullable<int> UserId { get; set; }
public System.DateTime CreatedDate { get; set; }
public virtual User User { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CartDetail> CartDetails { get; set; }
}
这是 CartDetail 类
public partial class CartDetail
{
public int Id { get; set; }
public int CartId { get; set; }
public int ProductId { get; set; }
public decimal Qty { get; set; }
public decimal Price { get; set; }
public System.DateTime CreatedDate { get; set; }
public virtual Cart Cart { get; set; }
}
谢谢
【问题讨论】:
-
可以添加类 Cart 和 CartDetail 的定义吗?
-
嗨@RomEh,我添加了购物车和购物车详细信息。谢谢
-
您没有在 json 中声明 CarDetail 数组。顺便说一句,这可能会有所帮助json2csharp.com
-
在 json 中,CartDetails 不是一个数组,它是一个对象,但是在你的 c# 代码中你说它是一个 ICollection
-
此外,它命名为 CartDetails,在您的 json 中命名为 CartDetail。
标签: c# json asp.net-web-api deserialization