我有一个JSON对象,看起来像这样。
{
"Errors":{
"err1":[
//* Array of err1 objects
],
"err2":[
//* Array of err2 objects
]
}
}
我使用这个对象来向PHP页面报告请求中发现的错误。
我想把这个对象转换成一个基本上像这样声明的vb.Net对象:
Public Class WebErrContainer
Public Errors as List(Of IWebError)
End Class
Public Class Err1
Implements IWebError
End Class
Public Class Err2
Implements IWebError
End Class
Public Interface IWebError
End Interface
我不知道我的实现是否足够好,我对vb.net还比较陌生,所以我现在在OOP方面的技能有点低。
就是这样…我想我已经尽我所能地解释了情况。
如果你需要更多的信息,我会给你的。
提前感谢您所能提供的任何帮助。谢谢
PD:我目前正在使用Newtonsoft的JSON.Net库。随意推荐一些其他库或方法来处理VB.NET.中的JSON
我这样做解决了这个问题:
Public Sub New(ByVal jsonText As String)
Dim jObject As JObject = jObject.Parse(jsonText )
Dim jErrors As JToken = jObject("Errors")
Dim jS = New JsonSerializer()
' This is the "temporal" dictionary that stores the errors like they are
' stored in JSON
Dim jsErrs As New Dictionary(Of String, List(Of Object))
' List that is going to be passed to the "Errors" field in the class
Dim lErrors As New List(Of IWebError)
jsErrs = jS.Deserialize(New JTokenReader(jErrors ), jsErrs .GetType)
If Not jsErrs Is Nothing Then
For Each errType As KeyValuePair(Of String, List(Of Object)) In jsErrs
For Each Err As Object In errType.Value
lErrors .Add(jS.Deserialize(New JTokenReader(Err), Type.GetType(errType.Key)))
Next
Next
End If
Me.Errors = lErrors
End Sub
可能最简单的解决方案是将Errors
设置为基于Err1
和Err2
:计算的只读属性
Public Class WebErrContainer
Public Readonly Property Errors as List(Of IWebError)
Get
Return (Ctype(Err1, IEnumerable(Of IWebError))).Concat(Err2).ToList
End Get
End Property
Public Err1 as List(Of Err1)
Public Err2 as List(Of Err2)
End Class
你能用Deserialize自动为你做这件事吗?或者有什么奇怪的事情发生了。我用过Newtsonsoft,我是这样做的(在c#中)
JsonConvert.DeserializeObject(Of MyJsonFromPHP)(jsonResponseText)
Public Class MyJsonFromPHP
Public Property Errors as ErrorCollection
End Class
Public Class ErrorCollection
Public Property err1 As List(Of Err1)
Public Property err2 As List(Of Err2)
End Class
Public Class Err1
Public Property code as Integer
Public Property message as String
End Class
我认为这可能会对您有所帮助。这里的strJSON是您的JSON字符串
Dim jsS As New JavaScriptSerializer : objPostData = jsS.DeserializeObject(strJSON)
之后你可以像这个一样迭代
For Each objTop As Object In objPostData
objDic = CType(objTop, Generic.Dictionary(Of String, Object))
dim strError as string = objDic.Item("Errors")
Next
如果您还需要,请告诉我