user1635564 user1635564 - 4 months ago 12 Question

Get the JSON Format using

Suggest me to get the JSON format as describe below using

var fieldtypes = {

name: { label: 'Name', type: 'text', icon: 'fa-user' },
firstname: { label: 'First name', type: 'text', icon: 'fa-user' },


I want to get this format in web-method that call in form of AJAX call.
I write the method for this but it doesn't generate JSON that describe in above.

VB.Net web-method

Public Class FormBuilder
Public Property label() As String
Public Property type() As String
Public Property icon() As String
End Class


Public Shared Function LogsheetDetail(LogMasterID As Integer) As String
Dim sCtrlTag As String = ""
Dim sDataType As String = ""
Dim finalVal As String = ""
Dim oDs As DataSet
Dim frmBuilder As New List(Of FormBuilder)()
oDs = GenUser.TempLogsheetDetails(Conn, LogMasterID)
If oDs.Tables(0).Rows.Count > 0 Then
For i = 0 To oDs.Tables(0).Rows.Count - 1
sDataType = oDs.Tables(0).Rows(i)("data_type").ToString()
Select Case sDataType
Case "Text"
frmBuilder.Add(New FormBuilder() With { _
.label = oDs.Tables(0).Rows(i)("parameter_name").ToString(), _
.type = "text", _
.icon = "fa-user" _

End Select

End If

Catch ex As Exception
Throw New Exception(ex.ToString)
If Not oDs Is Nothing Then oDs.Dispose()
End Try
Dim objJSSerializer As New System.Web.Script.Serialization.JavaScriptSerializer()

Dim jsonString As String = objJSSerializer.Serialize(frmBuilder)

Return jsonString


I believe the problem is that your code creates an array of objects instead of a single object. I assume you code is generating an output like this:

    { "label": "Name", "type": "text", "icon": "fa-user" },
    { "label": "First name", "type": "text", "icon": "fa-user" }

The ideal solution would be creating a dictionary instead of a list. However, the JsonSerializer class does not work very well with dictionaries and would need a workaround.

It would be simpler if you could use Newtonsoft Json instead of JavascriptSerializer. The following code generates the output you want, using the Newtonsoft Json NuGet package:

    Dim dic = New Dictionary(Of String, FormBuilder)

    dic.Add("name", New FormBuilder() With {
           .label = "name",
           .type = "text",
           .icon = "fa-user"

    dic.Add("firstname", New FormBuilder() With {
               .label = "firstname",
               .type = "text",
               .icon = "fa-user"

    Return Newtonsoft.Json.JsonConvert.SerializeObject(dic)