I wrote an article to help answer questions commonly asked in here:
Working with JSON in C# & VB[
^]
Your question is about serialization of class to raw JSON, something not covered in detail in the article, so I will answer here using Newtonsoft's
Json.NET[
^] library.
To make sure that your classes match the JSON structure, I've used a utility website
jsonutils[
^] (currently offline at the time of writing this answer - you can download and run the website locally:
GitHub - bladefist/JsonUtils[
^]). IT will generate the following set of classes:
Public Class ItmDet
<JsonProperty("txval")>
Public Property Txval As Integer
<JsonProperty("rt")>
Public Property Rt As Integer
End Class
Public Class Itm
<JsonProperty("num")>
Public Property Num As Integer
<JsonProperty("itm_det")>
Public Property ItmDet As ItmDet
End Class
Public Class Inv
<JsonProperty("inum")>
Public Property Inum As String
<JsonProperty("idt")>
Public Property Idt As String
<JsonProperty("val")>
Public Property Val As Integer
<JsonProperty("itms")>
Public Property Itms As Itm()
End Class
Public Class B2b
<JsonProperty("patry")>
Public Property Patry As String
<JsonProperty("inv")>
Public Property Inv As Inv()
End Class
Public Class Example
<JsonProperty("CompCode")>
Public Property CompCode As String
<JsonProperty("fp")>
Public Property Fp As String
<JsonProperty("gt")>
Public Property Gt As Integer
<JsonProperty("cur_gt")>
Public Property CurGt As Integer
<JsonProperty("b2b")>
Public Property B2b As B2b()
End Class
Then in the article link above I have a helper class for serializing and deserializing To/From JSON. Here is the class from the article:
Public Module JsonHelper
Public Function FromClass(Of T)(data As T,
Optional isEmptyToNull As Boolean = False,
Optional jsonSettings As JsonSerializerSettings = Nothing) As String
Dim response As String = String.Empty
If Not EqualityComparer(Of T).Default.Equals(data, Nothing) Then
response = JsonConvert.SerializeObject(data, jsonSettings)
End If
Return If(isEmptyToNull, (If(response = "{}", "null", response)), response)
End Function
Public Function ToClass(Of T)(data As String,
Optional jsonSettings As JsonSerializerSettings = Nothing) As T
Dim response = Nothing
If Not String.IsNullOrEmpty(data) Then
response = If(jsonSettings Is Nothing,
JsonConvert.DeserializeObject(Of T)(data),
JsonConvert.DeserializeObject(Of T)(data, jsonSettings))
End If
Return response
End Function
End Module
Now to use, it is simply as follows:
Sub Main()
Dim rawJson = "{""CompCode"":""COMP0001"",""fp"":""072018"",""gt"":0,""cur_gt"":0,""b2b"":[{""patry"":""ABC Company"",""inv"":[{""inum"":""00164"",""idt"":""01-07-2018"",""val"":525,""itms"":[{""num"":1,""itm_det"":{""txval"":500,""rt"":5}}]}]}]}"
Dim resultClass = JsonHelper.ToClass(Of Example)(rawJson)
Dim resultJson = JsonHelper.FromClass(resultClass)
End Sub