Cato Cato - 1 year ago 107 Question

Accessing nested object in from newtonsoft json

First off, apologies if this has already been posted. I have spent some time researching but haven't found a solution.

My goal is to access data from various JSON responses to web requests in I am having trouble with nested responses; an example:

dim JSON as string = '{"url2": {"href": ""}}'

I have the classes like so:

Public Class test1
Public Class url2
Public href As String
End Class
End Class

Deserialize the JSON:

Dim objURL1 As test1 = Newtonsoft.Json.JsonConvert.DeserializeObject(Of test1)(JSON)

This seems to work correctly, however I simply do not know how to access the
value, which is "" in this example.

dbc dbc
Answer Source

You are confusing two concepts: Nesting of .Net types and aggregation of instances of .Net objects. (Latter link is for c# but also applies to VB.NET.)

What you want is aggregation by inclusion, like so:

Public Class Url2
    Public Property href As String
End Class

Public Class Test1
    Public Property url2 as Url2
End Class

Then to access the href value do:

Dim objURL1 = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Test1)(JSON)
dim href = objURL1.url2.href

Sample fiddle.

For more background on nested types in .Net, see Why/when should you use nested classes in .net? Or shouldn't you?. If you're coming from Java, see also What are the fundamental differences between Java and C# in terms of inner/local/anonymous classes? which explains that .net nested types are not the same as Java inner classes.