2016-07-16 57 views
0

那麼,我想反序列化JSON到.Net對象。我爲它使用了一個類,但它看起來像拋出一個錯誤。如何使用JSON.NET在VB.NET上將JSON反序列化爲「半動態」對象?

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 

,然後,當我測試了一下,這表明「身份」中的「內容」都沒有找到。 Throwed Exception by UnitTesting

那麼如何讓content成員真的是動態的?

編輯

內容可能是這樣tooo

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

回答

0

你可能會考慮改變內容對象詞典(字符串,字符串)。這裏的例子: -

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

將內容轉換成詞典(字符串,字符串),你可以使用內容(「狀態」)獲得的慾望值。

參考:How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

UPDATE

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 
+0

它完成了這項工作。但有時當我訪問其他「404」網址時,響應會發生變化,並會出現錯誤。 (我更新了這篇文章)。當我創建一個新的測試單元時,它會拋出像這樣的異常http://i.imgur.com/gUBV6iX.png – Chris

+0

我建議你分開內容。請參閱上面的更新。希望這可以幫助。 :) –

+0

明白了。謝謝! – Chris