0

I am sending JSON from my Angular frontend (with HttpClient post) to my VB.NET backend but I cannot seem to deserialize it correctly.

JSON

{  
   "taxRate":0,
   "shipping":0,
   "items":
  [  
   {  
      "id":392184,
      "name":"",
      "price":0,
      "image":"",
      "quantity":1,
      "data":"sku1"
   },
   {  
      "id":338429,
      "name":"",
      "price":0,
      "image":"",
      "quantity":1,
      "data":"sku2"
   },
   {  
      "id":386646,
      "name":"",
      "price":0,
      "image":"",
      "quantity":1,
      "data":"sku3"
   }
  ]
}

My classes

Public Class CartDTO
  Public Property Shipping As Decimal
  Public Property TaxRate As Decimal
  Public Property Items() As CartItemDTO
End Class

Public Class CartItemDTO
  Public Property Id As Integer
  Public Property Name As String
  Public Property Image As String
  Public Property Price As Decimal
  Public Property Quantity As Integer
  Public Property Data As String
End Class

Controller function to catch this:

Public Sub PostValue(<FromBody()> ByVal value As Object)
'breakpoint
End Sub

If I put value As String then value is null.

If value As CartDTO then value is an empty CartDTO.

If value As Object then value is of type Newtonsoft.Json.Linq.JObject which has the correct data, but I can't work out how to easily get it into my DTO...

Trying this:

Dim ob = JsonConvert.DeserializeObject(Of CartDTO)(value)

...gives me System.InvalidCastException: 'Conversion from type 'JObject' to type 'String' is not valid.'

What am I missing?

Edit - or how can I receive the json as a string? Not sure why value is Nothing when I try that.

Andrew Hill
  • 2,165
  • 1
  • 26
  • 39
Sparrowhawk
  • 358
  • 1
  • 4
  • 11

1 Answers1

0

Ok got it, with a combination of these 2 answers.

Change DTO to

Public Class CartDTO
  Public Property Shipping As Decimal
  Public Property TaxRate As Decimal
  Public Property Items As List(Of CartItemDTO)
End Class

And do this:

Public Sub PostValue(<FromBody()> ByVal value As Object)
  Dim o = JsonConvert.SerializeObject(value)
  Dim ob = JsonConvert.DeserializeObject(Of CartDTO)(o)
  'ob is now a nicely filled CartDTO as expected
End Sub

It seems like there should be a better way... but this works.

Sparrowhawk
  • 358
  • 1
  • 4
  • 11