0

I am trying to deserialize json but couldnt get what I want. I would like to deserialize the json to C# object but I couldnt deserialize its children. I would like to share my code and ask for your opinion...

{
        "accessToken":"123",
        "requestId":"5mRIo6Y6epripoBA3YTM+ZDVgDVR2adB43euMJETguSboG0HT6j7Uje5mU0je5CF",
        "CreatedDate":"2019-07-24",
        "CartDetail":{
            "ProductId":"1",
            "Qty":"2",
            "Price":"3",
            "CreatedDate":"2019-07-24"
        }
}

this is the C# code that tries to deserialize

HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
Cart cart = JsonConvert.DeserializeObject<Cart>(jsonContent);

This code could deserialize inner object CartDetail. How can I fix this?

This is the Cart class

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; }
}

This is the CartDetail class

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; }
}

Thanks

Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189
  • 1
    Can you add the definition of the classes Cart and CartDetail ? – Rom Eh Jul 24 '19 at 07:32
  • 1
    Hi @RomEh, I added the Cart and CartDetail. Thank you – Arif YILMAZ Jul 24 '19 at 07:34
  • 2
    You are not declaring in the json an array of CarDetail. BTW, this could be helpful http://json2csharp.com/ – Cleptus Jul 24 '19 at 07:34
  • 3
    In the json, CartDetails is not an array, it's an object, but in your c# code u are saying thats it's an ICollection – JOSEFtw Jul 24 '19 at 07:36
  • 1
    Also, it named CartDetails and in your json it named CartDetail. – Dilshod K Jul 24 '19 at 07:38
  • 1
    The date should follow a well known format. Check [this question](https://stackoverflow.com/questions/10286204/the-right-json-date-format). All your numeric data is declared in the json as strings – Cleptus Jul 24 '19 at 07:51

2 Answers2

2

Simply copy the JSON and use Visual Studio's Paste Special feature:

enter image description here

It will generate the following classes for you:

public class Cart
{
    public string accessToken { get; set; }
    public string requestId { get; set; }
    public string CreatedDate { get; set; }
    public Cartdetail CartDetail { get; set; }
}

public class Cartdetail
{
    public string ProductId { get; set; }
    public string Qty { get; set; }
    public string Price { get; set; }
    public string CreatedDate { get; set; }
}

Then simply deserialize it:

enter image description here

FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46
  • I cannot change the classes, I am using Entity Framework. Classes were created automatically. – Arif YILMAZ Jul 24 '19 at 07:41
  • 2
    But the classes should match the data type and name with JSON in order to properly deserialize it. If there is a mismatch between classes and JSON then you'll have to override JSON.NET methods and manually map the fields. But I am not sure if it is a good solution. – FaizanHussainRabbani Jul 24 '19 at 07:44
  • @ArifYILMAZ for example, ProductId in JSON is a string but in the CartDetail class, it is declared as int. These kinds of mismatches will never allow proper deserialization. – FaizanHussainRabbani Jul 24 '19 at 07:46
2

Your JSON does not match your c# classes.

CartDetail is not an array in your JSON but you have declared it as an ICollection in your C# code.

Change your CartDetail from ICollection to CartDetail instead. Also, the c# property name needs to match the JSON property name (if you dont want to use the JsonProperty attribute) so rename CartDetails to CartDetail.

Btw, it seems like you are trying to deserialize directly to some "domain/business classes"? Try creating separate dtos and deserialize to them and then create your business objects from the dtos, it gets much cleaner then :)

So create new classes that you only use for serialization/deserialization and then create a factory or whatever that maps from the new dtos to your business objects. Separation of concerns FTW :).

JOSEFtw
  • 9,781
  • 9
  • 49
  • 67