簡體   English   中英

如何在VB.NET上使用JSON.NET將JSON反序列化為“半動態”對象?

[英]How to deserialize JSON to a “semi dynamic” object using JSON.NET on VB.NET?

好吧,我想將JSON反序列化為.Net對象。 我為此使用了一個類,但似乎拋出一個錯誤。

Me._konten包含此字符串

{
   "status": true,
   "content": {
       "status": "up",
       "ver": "3.0.1",
       "gen": "a"
   }
}

這是轉換器

    Public Async Function JSONify() As Task(Of APIResponseJSON)
        Dim hasil As Object = Await _
            Task.Run(Function()
                         Return JsonConvert.DeserializeObject(Of APIResponseJSON)(Me._Konten)
                     End Function)
        Return hasil
    End Function

因此,內容部分確實是不可預測的,它可能是數組或其他對象。 這是我上過的課:

  Public Class APIResponseJSON
       Public Property status As Boolean = False
       Public Property content As Object = New Object
  End Class

然后,當我對其進行測試時,這表明未找到“內容”中的“狀態”。 由UnitTesting引發異常

那么如何使content成員真正具有動態性呢?

編輯

內容可能像這樣

{
    "status": false,
    "content": {
        "detail": {
            "status": "Not Found",
            "code": 404,
            "text": "HTTP 404 (GET \/info)",
            "trace": ""
        }
    }
}

您可能考慮將內容對象更改為Dictionary(of String,String)。 這是例子:

Public Class APIResponseJSON
   Public Property status As Boolean = False
   Public Property content As New Dictionary(of String, String)
End Class

它將內容轉換為Dictionary(字符串,字符串),您可以使用Content(“ status”)獲得所需的值。

參考: 如何在ASP.NET中將JSON反序列化為簡單的Dictionary <string,string>?

更新

Public Class APIResponseJSON
   Public Property status As Boolean = False
   Public Property content As New Dictionary(of String, String)
   Public Property exception As New Dictionary(of String, Dictionary(of string, string))
End Class

您可以使用“狀態”將錯誤信息與數據分開。 例如:-

If obj.Status = True Then
   ' read from content
Else
   ' read from exception
End If

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM