我有一个看起来像这样的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
答案 0 :(得分:1)
最简单的解决方案可能是将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
答案 1 :(得分:1)
您是否可以使用反序列化为您自动执行,或者是否有一些奇怪的事情发生。我使用过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
答案 2 :(得分:0)
我认为这可能会对你有所帮助。 这里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
如果您想要其他任何内容,请告诉我