我试图使用JavaScriptSerializer
来解析一些json字符串来创建对象。我正在考虑实施这样的事情但我的运气却没有运气......
Dim object As New SomeObject
Dim js As New JavaScriptSerializer
someObject = js.Deserialize(Of Somebject)(jsonstr)
object1.var1 = someObject("somekey")
其中jsonstr
是json格式的数据。我无法使用任何第三方库,例如newtonsoft.json
等。
编辑:我取得了一些进展,因为我的班级,例如有财产"名称"我的json有关键" name"同时它会将字符串传递给objects属性,并且json文件具有任何值。
Dim object As SomeObject = js.Deserialize(Of SomeObject)(jsonstr)
Dim name As String = object.name //object now holds value for name
但如果我的json是这样的话。我怎样才能得到以下名称?
"value" : {
"validationFactors" : [
{
"name" : "remote_address",
"value" : "127.0.0.1"
}
]
}
如果我调用Deserialize来获取名称,例如我得到MissingMethodException 我是否需要更改我的虚拟对象?如果是这样的话?谢谢
答案 0 :(得分:1)
这是一个有效的例子:
Sub Main
Dim js As New JavaScriptSerializer()
Dim someObject As SomeObject = js.Deserialize(Of SomeObject)("{""A"":""Hello"",""B"":42}")
Console.WriteLine("A:={0}, B:={1}", someObject.A, someObject.B)
End Sub
Class SomeObject
Public Property A As String
Public Property B As Integer
End Class
输出:
A:=Hello, B:=42
但是,您似乎正在尝试像字典一样访问someObject
,而您可以使用以下字符进行访问:
Dim someObject As Dictionary(Of String, Object) = js.Deserialize(Of Dictionary(Of String, Object))("{""A"":""Hello"",""B"":42}")
Console.WriteLine("A:={0}, B:={1}", someObject("A"), someObject("B"))
与之前相同的输出。