Class-less JSON (Newtonsoft)

How to general valid JSON with Newtonsoft without a class

Newtonsoft gives quick and easy way to generate JSON by passing a serialisable class...

Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(myClassObj)

But there are times when you just want to create arbitary JSON data without the need to create a whole new class just for the purpose. For this we can use Newtonsoft.Json.Linq.JObject

Dim jObj As New Newtonsoft.Json.Linq.JObject() From {
  {"attr1", "First Attribute"},
  {"attr2", false}
}
Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(jObj)

And if you need an array, use Newtonsoft.Json.Linq.JArray

Dim jObj As New Newtonsoft.Json.Linq.JArray()
jObj.Add(New Newtonsoft.Json.Linq.JObject() From {{"attr1", "First Attribute"}, {"attr2", false}})
Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(jObj)

Added 06/05/2022 10:40