Chris Chris - 4 months ago 28
Vb.net Question

How to deserialize JSON to a "semi dynamic" object using JSON.NET on VB.NET?

Well, i want to deserialize the JSON into .Net object. I've using a class for it, but it seems like throwing an error.

Me._konten
contains this string

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


here's the converter

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


so, the content part is really unpredictable, it may be a array, or other object.
This was the class that i've made:

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


and then, when i test it, this shows that the "status" in the "content" are not found.
Throwed Exception by UnitTesting

So How to make the
content
member are really dynamic?

EDIT

the content may be like this tooo

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

Answer

You might consider change content object to Dictionary(of String, String). Here's the example:-

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

It will convert content into Dictionary(of String, string) and you can use Content("status") to get the desire value.

Reference: 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

You can separate the data with error message by using "Status". For example:-

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