我试图找出一个类/ struture来处理以下JSON格式:
{
"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"
}
]
}
我试过(只是SetValue部分):
<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
结果如下:System.NullReferenceException:对象引用未设置为对象的实例。
我能够使用结构序列化内部部分,但无法弄清楚如何包含外部名称(ReturnData,SetValue)而不需要求助于字符串构建:
<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 & "}"
我可能有也可能没有ReturnData和SetValue的数据(至少一个或两个)。我试图让序列化程序处理大部分格式,而不必检查空部分和单项数组。有什么建议吗?
答案 0 :(得分:0)
这样的事情(我只编写了SetValue,您可以使用相同的技术轻松添加ReturnData。
基本上,只需将两个数组包装在一个外部对象中(我称之为MethodCall,因为它就是它的样子)。
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