Search code examples
vb.netjson.net

How to add a new property to Json Object in VB.NET?


I want to add new properties in JSON object.

I did the following to get my result.

In MapJson.vb Class

Public Class MapJson
    Public Class item
        Public Property ColList As ColMap
    End Class

    Public Class ColMap
        Public Property inv As String
    End Class
End Class`

In a winform button click:

    Dim ColLst As New List(Of MapJson.ColMap)
    Dim ColItem As New MapJson.ColMap With {
       .inv = "ABC"
    }

    ColLst.Add(ColItem)

    Dim YearItem As New MapJson.item With {
        .ColList = ColLst.Single
    }
    Dim CreateNewJson As String = JsonConvert.SerializeObject(YearItem, Formatting.Indented)
    MsgBox(CreateNewJson)

The result I get is:

{
  "ColList": {
    "inv": "ABC"
  }
}

Now I want to add properties to ColList Object.
Properties can be anything so I can't predefine it in the class.

I want something Like this :

{
  "ColList": {
    "inv": "ABC",
    "anyname1": "anyStringValue1",
    "anyname2": "anyStringValue1",
    "anyname3": "anyStringValue1"
  }
}

I searched internet and found this.

Dim jo As JObject = JObject.FromObject(jsontext)

jo.Add("feeClass", "A")
jo.Add("feeClass1", "B")
jo.Add("feeClass2", "C")
jo.Add("feeClass3", "D")

MsgBox(jo.ToString)

This works properly but I don't know how to add it to the ColList Object.
Thank you for you help in advance. :)


Solution

  • If you know the property names ahead of time, you could just create an anonymous type to serialize:

     Dim YearItem = New With {
        .ColList = New With {
          .inv = "ABC"
          .anyname1 = "anyStringValue1"
          .anyname2 = "anyStringValue1"
          .anyname3 = "anyStringValue1"
        }
     }
    

    Crucially, the first line of the code doesn't state MapJson.item etc, it just says New With {

    You don't really need your classes with this, if all youre doing is creating them for serialization purposes, it's probably neater to just create an anonymous one


    If you don't know them ahead of time, replace the ColMap with a dictionary:

    Dim x = New With {
      .ColList = New Dictionary(Of String, String)
    }
    
    x.ColList.Add("inv", "ABC")
    x.ColList.Add("anyname1", "anyStringValue1")
    x.ColList.Add("anyname2", "anyStringValue1")
    x.ColList.Add("anyname3", "anyStringValue1")
    

    Though this example doesn't demo that (clearly I do know them ahead of time because it wrote them into the code).. perhaps a loop that adds a list will be used in production


    PS if youre desperate to keep those classes:

    Public Class MapJson
        Public Class item
            Public Property ColList As Dictionary(Of String, String)
        End Class
    End Class`