Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON array using vb.net

How to create this JSON array using vb.net array

var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};
like image 937
Bader Avatar asked Mar 05 '12 08:03

Bader


3 Answers

As you're using .NET 2.0 you have to use the JSON libary by James, with download at Codeplex (version for .NET 2.0).

An example of using Json.NET

Add a reference to Newtonsoft.Json, and an Import Newtonsoft.Json in your class.

Example:

Import Newtonsoft.Json

Dim product As New Product()
product.Name = "Captopril"
product.Expiry = New DateTime(2008, 12, 28)
product.Price = 3.99D
product.Sizes = New String() {"Small", "Medium", "Large"}


'Call SeralizeObject to convert the object to JSON string'
Dim output As String = JavaScriptConvert.SerializeObject(product)

The output variable will hold the value:

{
  "Name": "Captopril",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}
like image 69
Josua Marcel C Avatar answered Oct 05 '22 23:10

Josua Marcel C


Public Class Student
    Public Property value As String
    Public Property name As Integer
End Class

On Page_Load:

'creating sample student ojects
    Dim obj1 As New Student() With {.value = "Mick Jagger", .name = 21}
    Dim obj2 As New Student() With {.value = "Johnny Storm", .name = 43}
    Dim obj3 As New Student() With {.value = "Richard Hatch", .name = 46}
    Dim obj4 As New Student() With {.value = "Kelly Slater", .name = 54}
    'adding student objects to list
    Dim objStudentList As New List(Of Student)() From { obj1,obj2, obj3, obj4}

    Dim objJSSerializer As New System.Web.Script.Serialization.JavaScriptSerializer()

    'Serialization .NET Object to JSON
    strJSON = objJSSerializer.Serialize(objStudentList)

    Dim csname2 As String = "ButtonClickScript"
    Dim cstype As Type = Me.GetType()
    Dim cstext2 As New StringBuilder()
    Dim cs As ClientScriptManager = Page.ClientScript
    cstext2.Append("<script type=""text/javascript""> var data = {items: " + strJSON)
    cstext2.Append(" }; </")
    cstext2.Append("script>")
    cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), False)
like image 25
Andrea Colabufalo Avatar answered Oct 05 '22 23:10

Andrea Colabufalo


Check out the visual studio gallery extension called JSON.net or go to their codeplex page (JSON on codeplex)

like image 21
LongArm Avatar answered Oct 06 '22 00:10

LongArm