Need a class/structure to serialize JSON in VB.net
I am trying to figure out a class/struture to handle the following J开发者_JAVA技巧SON format:
{
"ReturnData": [
{
"id": "msg2DoesNotExistName",
"value": "value 1",
"userExists": 2
},
{
"id": "msg2DoesNotExistName",
"value": "Value 2",
"userExists": 2
}
],
"SetValue": [
{
"id": "msg2DoesNotExistName",
"value": "value 1"
},
{
"id": "msg2DoesNotExistName",
"value": "Value 2"
}
]
}
I have tried (just the SetValue portion):
<Serializable()> _
Public Class Stuff
Public SetValue() As ArrayList
End Class
Public Function TestSerial3(ByVal somevar As String) As String
Dim s As New JavaScriptSerializer()
Dim ret As String
Dim b As New SaveType()
Dim p1 As New Stuff
b = New SaveType
b.id = "ctl00_number_1"
b.value = "Test1"
p1.SetValue(0).Add(b)
b = New SaveType
b.id = "ctl100_number_2"
b.value = "Test2"
p1.SetValue(1).Add(b)
ret = s.Serialize(p1)
return ret
end function
This is the result: System.NullReferenceException: Object reference not set to an instance of an object.
I am able to serialize the inside portion using a structure, but cannot figure out how to include the outer name (ReturnData, SetValue) without resorting to string building:
<Serializable()> _
Public Structure UserExistsType
Public id As String
Public value As String
Public userExists As Integer
End Structure
Dim b(1) As UserExistsType
b(0).id = "msg2DoesNotExistName"
b(0).value = "value 1"
b(0).userExists = 2
b(1).id = "msg2DoesNotExistName"
b(1).value = "Value 2"
b(1).userExists = 2
ret = s.Serialize(b)
ret = "{" & Chr(34) & "ReturnData" & Chr(34) & ":" & ret & "}"
I may or may not have Data for ReturnData and SetValue (one or both at a minimum). I am trying to let the serializer handle most of the formatting without having to check for empty sections and single-item arrays. Any suggestions?
How bout something like this (I only coded up SetValue, you can easily add ReturnData using the same technique.
Essentially, just wrap your two arrays in an outer object (I called mine MethodCall, because that's what it looks like).
Imports System.Runtime.Serialization
Imports System.Web.script.serialization
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Debug.Print(TestSerial3())
End Sub
Public Function TestSerial3() As String
Dim s As New JavaScriptSerializer()
Dim ret As String
Dim r = New MethodCall
r.SetValue(0) = New SetValue
With r.SetValue(0)
.id = "ctl00_number_1"
.value = "Test1"
End With
r.SetValue(0) = New SetValue
With r.SetValue(0)
.id = "ctl100_number_2"
.value = "Test2"
End With
ret = s.Serialize(r)
Return ret
End Function
End Class
<Serializable()> _
Public Class ReturnData
Public id As String
Public value As String
Public userExists As Integer
End Class
<Serializable()> _
Public Class SetValue
Public id As String
Public value As String
End Class
<Serializable()> _
Public Class MethodCall
Public SetValue(1) As SetValue
Public returnData(2) As ReturnData
End Class
精彩评论