我无法弄清楚如何遍历对象以检索在JSON字符串中发送的错误列表。我有一个For Each循环在我的JSON中的每个密钥对值,但第三个密钥对是密钥对的对象。我无法使用相同的For Each结构访问它们(如果我循环访问对象,我可以访问它们但是如果可能的话希望保持一致..我的'Case is“错误”case语句是我想迭代错误对象的地方但是我不知道该怎么做..这是我的代码..我希望有人可以帮助..
示例JSON:
{ “成功”: “真”, “api_reference”:3821, “错误”:[{ “记录”: “地主”, “RECORD_ID”: “ - 16 :: 1 :: LPMB40-2385DDDC”,”错误“:”请 确保电子邮件字段已存在 完成 “ ”ERROR_CODE“: ”33101“},{ ”记录“: ”地主“, ”RECORD_ID“: ” - 16 :: 1 :: LPMB40-2385DDDC“, ”错误“:” 请 确保电子邮件字段是有效的电子邮件 地址”, “ERROR_CODE”: “33102”}]}
Dim jss = New JavaScriptSerializer()
Dim data = jss.Deserialize(Of Object)(responseFromServer)
Dim strSuccess = "", strAPIReference = ""
Dim intExpiresIn = 0
Dim ErrorsObject As Object
For Each kvp As KeyValuePair(Of String, Object) In data
Select Case kvp.Key
Case Is = "success"
strSuccess = kvp.Value
Case Is = "api_reference"
strAPIReference = kvp.Value
Case Is = "errors"
ErrorsObject = kvp.Value
For Each errorskvp As KeyValuePair(Of String, Object) In ErrorsObject
Next
End Select
Next
答案 0 :(得分:1)
我建议这样强类型,这样你就可以将json反序列化为真实对象并使用对象属性。这样,读取值和循环错误等更容易:
类:
Public Class JsonResponse
Public Property Success As Boolean
Public Property Api_reference As String
Public Property Errors As IEnumerable(Of JsonError)
End Class
Public Class JsonError
Public Property Record As String
Public Property Record_Id As String
Public Property [Error] As String
Public Property Error_Code As String
End Class
反序列化和使用:
Dim j As New JavaScriptSerializer()
Dim data As JsonResponse = j.Deserialize(Of JsonResponse)(responseFromServer)
If Not data.Success Then
For Each myError As JsonError In data.Errors
Next
End If