JSON <NonSerialized()> not working VB.NET? - json

I'm having a bit of trouble with some JSON serialization that I'm doing in VB.NET.
Basically, I have two classes.
MenuItemDataLong
And MenuItemDataShort
MenuItemDataLong inherits MenuItemDataShort.
Code:
MenuItemDataShort.vb
<Serializable()>
Public Class MenuItemDataShort
Public Display_Name As String = ""
Public Display_Description As String = ""
Public Display_Price As Single = 0.0
Public SELECTED_NAME As Integer = 0
Public SELECTED_PRICE As Integer = 0
Public WEB_IMAGE As String = ""
Public WEB_IMAGE_WIDTH As Integer = 0
Public WEB_IMAGE_HEIGHT As Integer = 0
Public PAGE_NUM As Integer = 0
Public CELL_ID As Integer = 0
Public SHOW_BMP_FILE As Boolean = False
Public SHOW_DESCRIPT As Boolean = False
Public SHOW_PRICE As Boolean = False
Public SHOW_LONG_DESC As Boolean = False
Public LONG_DESC_FONT_NAME As String
Public LONG_DESC_FONT_BOLD As Boolean
Public LONG_DESC_FONT_UNDERLINE As Boolean
Public LONG_DESC_FONT_ITALIC As Boolean
Public LONG_DESC_FONT_COLOR_R As Integer
Public LONG_DESC_FONT_COLOR_G As Integer
Public LONG_DESC_FONT_COLOR_B As Integer
Public LONG_DESC_FONT_SIZE As Integer
Public DESC_FONT_NAME As String
Public DESC_FONT_BOLD As Boolean
Public DESC_FONT_UNDERLINE As Boolean
Public DESC_FONT_ITALIC As Boolean
Public DESC_FONT_COLOR_R As Integer
Public DESC_FONT_COLOR_G As Integer
Public DESC_FONT_COLOR_B As Integer
Public DESC_FONT_SIZE As Integer
Public PRICE_FONT_NAME As String
Public PRICE_FONT_BOLD As Boolean
Public PRICE_FONT_UNDERLINE As Boolean
Public PRICE_FONT_ITALIC As Boolean
Public PRICE_FONT_COLOR_R As Integer
Public PRICE_FONT_COLOR_G As Integer
Public PRICE_FONT_COLOR_B As Integer
Public PRICE_FONT_SIZE As Integer
Public DESC_X As Integer
Public DESC_Y As Integer
Public PRICE_X As Integer
Public PRICE_Y As Integer
Public IMAGE_X As Integer
Public IMAGE_Y As Integer
Public LONG_DESC_X As Integer
Public LONG_DESC_Y As Integer
End Class
MenuItemDataLong.vb
<Serializable()>
Public Class MenuItemDataLong
Inherits MenuItemDataShort
<NonSerialized()>
Public DESCRIPT As String
<NonSerialized()>
Public OO_Alias As String
<NonSerialized()>
Public LONG_DESCRIPTION As String
<NonSerialized()>
Public RECIPE_DESCRIPTION As String
<NonSerialized()>
Public BMP_FILE As String
<NonSerialized()>
Public PRICE1, PRICE2, PRICE3, PRICE4, PRICE5, PRICE6, PRICE7, PRICE8, PRICE9, PRICE10, PRICE11, PRICE12, PRICE13, PRICE14 As Single
End Class
I then have the MenuItemDataLong object stored somewhere. The excess data in the MenuItemDataLong class is necessary in application, but is not necessary once the file is serialized. So, I'm trying to take the MenuItemDataLong and cast it back down to a MenuItemDataShort and serialize it. However, Whenever I do I end up with all of the data from MenuItemDataLong still in it, even with the NonSerialized() tags.
Anyone know what I'm doing wrong?..
EDIT:
If anyone is curious, this is how I'm serializing:
Dim sItemData As MenuItemDataShort = CType(ItemData, MenuItemDataShort)
Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer
Dim Serialized As String = Serializer.Serialize(sItemData)

You are basically using the wrong attribute. From MSDN - NonSerialized:
When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized.
It does not mention the JavaScriptSerializer. There is another attribute: <ScriptIgnore> which seems to work. Using simplified classes and a mix of actual Properties and Fields:
Imports System.Web.Script.Serialization
<Serializable()>
Public Class MenuItemShort
Public Property Name As String = ""
Public Description As String = ""
End Class
<Serializable()>
Public Class MenuItemLong
Inherits MenuItemShort
<ScriptIgnore>
Public Property Foo As String
<ScriptIgnore>
Public Bar As String
Public Property Value As Integer
End Class
Test Code:
Dim mi As New MenuItemLong With {.Name = "foo",
.Description = "a foo item",
.Foo = "ghost in the machine",
.Bar = "bar",
.Value = 42}
Dim miS As MenuItemShort = DirectCast(mi, MenuItemShort)
Dim jser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jss As String = jser.Serialize(miS)
Console.WriteLine(jss)
Output:
{"Description":"a foo item","Value":42,"Name":"foo"}
There are other ways to ignore certain properties using NewtonSoft's JSON.Net.

Related

Why I get this JSON Deserialize Object error message

I call an API which return a JSON. This is the API call:
https://wax.api.atomicassets.io/atomicmarket/v1/sales?state=1&collection_name=hotwheels&template_id=353670&page=1&limit=1&order=asc&sort=price&timestamp=1654317900790
I ran the JSON result on this website to generate the class :
https://json2csharp.com/
After I converted the result to VB.net from the Telerik conversion tool:
https://converter.telerik.com/
It gave me the following class which I included in a class called : HWMarketplace
Public Class Asset
Public Property contract As String
Public Property asset_id As String
Public Property owner As String
Public Property is_transferable As Boolean
Public Property is_burnable As Boolean
Public Property collection As Collection
Public Property schema As Schema
Public Property template As Template
Public Property mutable_data As MutableData
Public Property immutable_data As ImmutableData
Public Property template_mint As String
Public Property backed_tokens As List(Of Object)
Public Property burned_by_account As Object
Public Property burned_at_block As Object
Public Property burned_at_time As Object
Public Property updated_at_block As String
Public Property updated_at_time As String
Public Property transferred_at_block As String
Public Property transferred_at_time As String
Public Property minted_at_block As String
Public Property minted_at_time As String
Public Property sales As List(Of Object)
Public Property auctions As List(Of Object)
Public Property prices As List(Of Price)
Public Property data As Data
Public Property name As String
End Class
Public Class Collection
Public Property collection_name As String
Public Property name As String
Public Property img As String
Public Property author As String
Public Property allow_notify As Boolean
Public Property authorized_accounts As List(Of String)
Public Property notify_accounts As List(Of Object)
Public Property market_fee As Double
Public Property created_at_block As String
Public Property created_at_time As String
End Class
Public Class Data
Public Property eula As String
Public Property make As String
Public Property name As String
Public Property legal As String
Public Property model As String
Public Property video As String
Public Property cardid As String
Public Property rarity As String
Public Property backimg As String
Public Property designer As String
Public Property collection As String
Public Property redeemable As Integer
Public Property description As String
<Newtonsoft.Json.JsonProperty("redeem date")>
Public Property RedeemDate As String
<Newtonsoft.Json.JsonProperty("release date")>
Public Property ReleaseDate As String
<Newtonsoft.Json.JsonProperty("year released")>
Public Property YearReleased As String
Public Property market_contract As String
Public Property assets_contract As String
Public Property sale_id As String
Public Property seller As String
Public Property buyer As Object
Public Property offer_id As String
Public Property price As Price
Public Property listing_price As String
Public Property listing_symbol As String
Public Property assets As List(Of Asset)
Public Property maker_marketplace As String
Public Property taker_marketplace As Object
Public Property collection_name As String
Public Property is_seller_contract As Boolean
Public Property updated_at_block As String
Public Property updated_at_time As String
Public Property created_at_block As String
Public Property created_at_time As String
Public Property ordinality As String
Public Property state As Integer
End Class
Public Class Format
Public Property name As String
Public Property type As String
End Class
Public Class ImmutableData
Public Property eula As String
Public Property make As String
Public Property name As String
Public Property legal As String
Public Property model As String
Public Property video As String
Public Property cardid As String
Public Property rarity As String
Public Property backimg As String
Public Property designer As String
Public Property collection As String
Public Property redeemable As Integer
Public Property description As String
<Newtonsoft.Json.JsonProperty("redeem date")>
Public Property RedeemDate As String
<Newtonsoft.Json.JsonProperty("release date")>
Public Property ReleaseDate As String
<Newtonsoft.Json.JsonProperty("year released")>
Public Property YearReleased As String
End Class
Public Class MutableData
End Class
Public Class Price
Public Property token_contract As String
Public Property token_symbol As String
Public Property token_precision As Integer
Public Property median As Object
Public Property amount As String
End Class
Public Class Price2
Public Property market_contract As String
Public Property token As Token
Public Property median As String
Public Property average As String
Public Property suggested_median As String
Public Property suggested_average As String
Public Property min As String
Public Property max As String
Public Property sales As String
End Class
Public Class Root
Public Property success As Boolean
Public Property data As List(Of Data)
Public Property query_time As Long
End Class
Public Class Schema
Public Property schema_name As String
Public Property format As List(Of Format)
Public Property created_at_block As String
Public Property created_at_time As String
End Class
Public Class Template
Public Property template_id As String
Public Property max_supply As String
Public Property is_transferable As Boolean
Public Property is_burnable As Boolean
Public Property issued_supply As String
Public Property immutable_data As ImmutableData
Public Property created_at_time As String
Public Property created_at_block As String
End Class
Public Class Token
Public Property token_symbol As String
Public Property token_precision As Integer
Public Property token_contract As String
End Class
Then from my VB.net code, I run these lines :
The variable strURL is declare previously in my code and it's the URL mentioned at the beginning of my message
Dim strJson As String = String.Empty
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(strURL), HttpWebRequest)
myHttpWebRequest.Timeout = 500000
With myHttpWebRequest
.Method = "GET"
.ContentType = "application/json"
.Accept = "application/json"
End With
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
strJson = New StreamReader(myHttpWebResponse.GetResponseStream()).ReadToEnd()
myHttpWebResponse.Dispose()
Dim myNFT As HWMarketplace.Root = JsonConvert.DeserializeObject(Of HWMarketplace.Root)(strJson)
And I get this error:
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
ex.Message :
"Unexpected character encountered while parsing value: {. Path 'data[0].collection', line 1, position 5018."
I would need a bit of help figuring why it doesn't work? I generated the class from the result, it should be ready to deserialize it with success.
I did the same process for other methods in that same API and it worked perfectly but this one seems to cause problems.
Any help would be appreciated.
Thank you.

how can I parse the google books api and access the class properties (vb.net)

I'm trying to access Googles book api and just populate textboxes with the information.
Here's an example of the API json: [https://www.googleapis.com/books/v1/volumes?q=isbn:9780979799006]
I used Visual Studio's Paste Special to create the Class. Here it is:
Public Class GoogleBookData
Public Class Rootobject
Public Property kind As String
Public Property totalItems As Integer
Public Property items() As Item
End Class
Public Class Item
Public Property kind As String
Public Property id As String
Public Property etag As String
Public Property selfLink As String
Public Property volumeInfo As Volumeinfo
Public Property saleInfo As Saleinfo
Public Property accessInfo As Accessinfo
Public Property searchInfo As Searchinfo
End Class
Public Class Volumeinfo
Public Property title As String
Public Property subtitle As String
Public Property publishedDate As String
Public Property description As String
Public Property industryIdentifiers() As Industryidentifier
Public Property readingModes As Readingmodes
Public Property pageCount As Integer
Public Property printType As String
Public Property categories() As String
Public Property maturityRating As String
Public Property allowAnonLogging As Boolean
Public Property contentVersion As String
Public Property panelizationSummary As Panelizationsummary
Public Property imageLinks As Imagelinks
Public Property language As String
Public Property previewLink As String
Public Property infoLink As String
Public Property canonicalVolumeLink As String
End Class
Public Class Readingmodes
Public Property text As Boolean
Public Property image As Boolean
End Class
Public Class Panelizationsummary
Public Property containsEpubBubbles As Boolean
Public Property containsImageBubbles As Boolean
End Class
Public Class Imagelinks
Public Property smallThumbnail As String
Public Property thumbnail As String
End Class
Public Class Industryidentifier
Public Property type As String
Public Property identifier As String
End Class
Public Class Saleinfo
Public Property country As String
Public Property saleability As String
Public Property isEbook As Boolean
End Class
Public Class Accessinfo
Public Property country As String
Public Property viewability As String
Public Property embeddable As Boolean
Public Property publicDomain As Boolean
Public Property textToSpeechPermission As String
Public Property epub As Epub
Public Property pdf As Pdf
Public Property webReaderLink As String
Public Property accessViewStatus As String
Public Property quoteSharingAllowed As Boolean
End Class
Public Class Epub
Public Property isAvailable As Boolean
End Class
Public Class Pdf
Public Property isAvailable As Boolean
End Class
Public Class Searchinfo
Public Property textSnippet As String
End Class
End Class
I call this function to read the stream and get the Class data:
Public Shared Function getGoogleBookData(ByVal sSku As String) As GoogleBookData
Dim result As String = Nothing
Dim url As String = "https://www.googleapis.com/books/v1/volumes?q=isbn:"
url &= sSku
Dim request As HttpWebRequest = WebRequest.Create(url)
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader = Nothing
Dim myJson As String = Nothing
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
myJson = reader.ReadToEnd
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim myGBookData As New GoogleBookData
myGBookData = serializer.Deserialize(Of GoogleBookData)(myJson)
Return myGBookData
End Function
I call the function:
Dim gsSearchSku as String = "9780979799006"
Dim myGItem As New GoogleBookData
myGItem = getGoogleBookData(gsSearchSku)
Then, I've tried several things to try to access any data in the Class:
I know this doesn't work but put it here so you can get an idea of what I'm trying.
Dim sTitle as String = myGItem.Item.Title
I can't even run it. GoogleBookData.item is a class type and cannot be used as an expression.
No idea where to go from here.
Any help would be greatly appreciated!!

VB.Net_Having Problem with reading a token from JSON

I'm making a program that reads weather data from open weather map API
Here's the response(json):
coord
lon -0.1257
lat 51.5085
weather
0
id 802
main "Clouds"
description "scattered clouds"
icon "03d"
base "stations"
main
temp 22.43
feels_like 22.4
temp_min 19.82
temp_max 24.21
pressure 1021
humidity 64
visibility 10000
wind
speed 4.12
deg 270
clouds
all 40
dt 1625834363
sys
type 2
id 2006068
country "GB"
sunrise 1625802859
sunset 1625861805
timezone 3600
id 2643743
name "London"
cod 200
and here is the code I use to select tokens from json:
Imports System.Net
Imports System.IO
Imports Newtonsoft.Json.Linq
Public deg As String = Chr(176)
Public iconid As String = ""
Public locationstr As String
Public ApiKey As String = "MYAPIKEY"
#Region "Conditions"
Public windspeedMPS As String = ""
Public humidity As String = ""
Public description As String
Public cloudiness As String = ""
Public temp As String = ""
Public City As String = ""
#End Region
Public Sub getweather(ByVal key As String)
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" & locationstr & "&appid=" & ApiKey & "&lang=en&units=metric"), HttpWebRequest)
Dim res As HttpWebResponse = DirectCast(req.GetResponse, HttpWebResponse)
Dim reader As New StreamReader(res.GetResponseStream)
Dim serverresponse As String = reader.ReadToEnd
Dim json As String = serverresponse
Dim obj As JObject = JObject.Parse(json)
Try
windspeddMPS = obj.SelectToken("wind").SelectToken("speed")
humidity = obj.SelectToken("main").SelectToken("humidity")
description = obj.SelectToken("weather").SelectToken("description")
cloudiness = obj.SelectToken("clouds").SelectToken("all")
temp = obj.SelectToken("main").SelectToken("temp")
City = obj.SelectToken("name")
iconid = obj.SelectToken("weather").SelectToken("icon")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I can select all the tokens except "description"(weather condition within a group) and "icon"(weather condition icon id) tokens.
For reference, here is the documentation for the web API you're using: https://openweathermap.org/current
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. If you were to do this, then you would get something that looks like the following:
Public Class Rootobject
Public Property coord As Coord
Public Property weather() As Weather
Public Property base As String
Public Property main As Main
Public Property visibility As Integer
Public Property wind As Wind
Public Property clouds As Clouds
Public Property dt As Integer
Public Property sys As Sys
Public Property timezone As Integer
Public Property id As Integer
Public Property name As String
Public Property cod As Integer
End Class
Public Class Coord
Public Property lon As Single
Public Property lat As Single
End Class
Public Class Main
Public Property temp As Single
Public Property feels_like As Single
Public Property temp_min As Single
Public Property temp_max As Single
Public Property pressure As Integer
Public Property humidity As Integer
End Class
Public Class Wind
Public Property speed As Single
Public Property deg As Integer
End Class
Public Class Clouds
Public Property all As Integer
End Class
Public Class Sys
Public Property type As Integer
Public Property id As Integer
Public Property message As Single
Public Property country As String
Public Property sunrise As Integer
Public Property sunset As Integer
End Class
Public Class Weather
Public Property id As Integer
Public Property main As String
Public Property description As String
Public Property icon As String
End Class
From here, you can deserialize the JSON response to the Rootobject class which in turn you have access to strongly typed objects to get your values:
' ... HTTP request to get JSON
Dim jsonObject = JsonConvert.DeserializeObject(Of Rootobject)(json)
Console.WriteLine(jsonObject.clouds.all)

How To Deserialize JSON in vb,net with Multiple objects

Below is a json file that needs to be deserialized and to be stored in different variables.
With this current json, which is returned by an API, I am unable to deserialize because it gives me and error -
Please help me on deserializing this particular json
I have added the code i used, but it returns wrong values and null reference.
{
"result": {
"candidates": [
{
"similarity": 0.1330482513,
"person_id": "75741ea3-4d9b-4e25-8460-16444ee39946",
"descriptor_id": "2f228007-350e-4d58-9897-4b62e9978081",
"user_data": "Без названия (9)",
"external_id": null
}
],
"face": {
"id": "a1b224a3-60c6-4733-9bbc-136d53ea011c",
"score": 0.9320185781
}
},
"timestamp": 1569957900.1488559,
"source": "search",
"event_type": "match",
"authorization": {
"token_id": "71f9b3e0-51b1-480f-93b9-0e76e260bcbc",
"token_data": "first token"
},
"template": {
"descriptor_id": "a1b224a3-60c6-4733-9bbc-136d53ea011c"
},
"candidate": {
"list_id": "6e64e600-cd77-4894-940e-6f7022d8aba8",
"list_data": "FaceStream_search_list(DON'T DELETE)",
"list_type": 1
}
}
I have tried :
Public Class Rootobject
Public Property result As Result
Public Property timestamp As Single
Public Property source As String
Public Property event_type As String
Public Property authorization As Authorization
Public Property template As Template
Public Property candidate As Candidate1
End Class
Public Class Result
Public Property candidates() As Candidate
Public Property face As Face
End Class
Public Class Face
Public Property id As String
Public Property score As Single
End Class
Public Class Candidate
Public Property similarity As Double
Public Property person_id As String
Public Property descriptor_id As String
Public Property user_data As String
Public Property external_id As Object
End Class
Public Class Authorization
Public Property token_id As String
Public Property token_data As String
End Class
Public Class template
Public Property descriptor_id As String
End Class
Public Class Candidate1
Public Property list_id As String
Public Property list_data As String
Public Property list_type As Integer
End Class
''And used
Dim Candidatess As New Candidate
Candidatess = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Candidate)((JObject.Parse(e.Message)).ToString)
msg(Candidatess.similarity.ToString)
msg(Candidatess.descriptor_id.ToString)
msg(Candidatess.person_id.ToString)
''REturns me Null
Public Class Candidate
Public Property similarity As Double
Public Property person_id As String
Public Property descriptor_id As String
Public Property user_data As String
Public Property external_id As Object
End Class
Public Class Face
Public Property id As String
Public Property score As Double
End Class
Public Class Result
Public Property candidates As Candidate()
Public Property face As Face
End Class
Public Class Authorization
Public Property token_id As String
Public Property token_data As String
End Class
Public Class Template
Public Property descriptor_id As String
End Class
Public Class Candidate
Public Property list_id As String
Public Property list_data As String
Public Property list_type As Integer
End Class
Public Class Candidates
Public Property result As Result
Public Property timestamp As Double
Public Property source As String
Public Property event_type As String
Public Property authorization As Authorization
Public Property template As Template
Public Property candidate As Candidate
End Class
Public Function GetData(ApiEndpoint As Uri, ApiToken As String)
Dim origResponse As HttpWebResponse = Nothing
Dim objResponse As HttpWebResponse = Nothing
Dim origReader As StreamReader = Nothing
Dim objReader As StreamReader = Nothing
Dim origRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(ApiEndpoint), HttpWebRequest)
origRequest.Headers.Add("Authorization", "Basic " & ApiToken)
origRequest.AllowAutoRedirect = False
origRequest.Method = "GET"
'Call the API and get the JSON Response data
origResponse = DirectCast(origRequest.GetResponse(), HttpWebResponse)
Dim Stream As Stream = origResponse.GetResponseStream()
Dim sr As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))
Dim myJsonResponse As String = sr.ReadToEnd()
'Deserialize the Json
Dim objFormResults As Result = JsonConvert.DeserializeObject(Of Result)(myJsonResponse)
'loop through the results
End Function

How do you parse this JSON data?

I have this JSON data that I would like to parse but I'm not sure how to go about it.
Here's the JSON:
{
"input":{
"lat":32.761125,
"lon":-96.791339
},
"results":[
{
"block_fips":"481130204001105",
"bbox":[
-96.79587,
32.753273,
-96.787714,
32.76218
],
"county_fips":"48113",
"county_name":"Dallas",
"state_fips":"48",
"state_code":"TX",
"state_name":"Texas",
"block_pop_2015":2,
"amt":"AMT004",
"bea":"BEA127",
"bta":"BTA101",
"cma":"CMA009",
"eag":"EAG005",
"ivm":"IVM009",
"mea":"MEA032",
"mta":"MTA007",
"pea":"PEA008",
"rea":"REA005",
"rpc":"RPC004",
"vpc":"VPC004"
}
]
}
I used the Visual Studio tool, Edit -> Paste Special -> Paste as JSON classes, to convert this JSON in classes and it gave me this class structure:
Public Class Rootobject
Public Property input As Input
Public Property results() As Result
End Class
Public Class Input
Public Property lat As Single
Public Property lon As Single
End Class
Public Class Result
Public Property block_fips As String
Public Property bbox() As Single
Public Property county_fips As String
Public Property county_name As String
Public Property state_fips As String
Public Property state_code As String
Public Property state_name As String
Public Property block_pop_2015 As Integer
Public Property amt As String
Public Property bea As String
Public Property bta As String
Public Property cma As String
Public Property eag As String
Public Property ivm As String
Public Property mea As String
Public Property mta As String
Public Property pea As String
Public Property rea As String
Public Property rpc As String
Public Property vpc As String
End Class
So then what I did to try and parse the data is:
Dim MyJSON As String = JsonAbove
Dim jss As New JavaScriptSerializer()
Dim dict = jss.Deserialize(Of Result)(rawresp)
MsgBox(dict.state_name)
All I get is a blank MessageBox with no results.
Am I doing something wrong?
Use List Of Objects instead of array in your class. I have done two changes One in the rootobject for results and other in the result class for bbox
Public Class Rootobject
Public Property input As Input
Public Property results As List(Of Result)
End Class
Public Class Input
Public Property lat As Single
Public Property lon As Single
End Class
Public Class Result
Public Property block_fips As String
Public Property bbox As List(Of Single)
Public Property county_fips As String
Public Property county_name As String
Public Property state_fips As String
Public Property state_code As String
Public Property state_name As String
Public Property block_pop_2015 As Integer
Public Property amt As String
Public Property bea As String
Public Property bta As String
Public Property cma As String
Public Property eag As String
Public Property ivm As String
Public Property mea As String
Public Property mta As String
Public Property pea As String
Public Property rea As String
Public Property rpc As String
Public Property vpc As String
End Class
Then access the properties
Dim jss As New JavaScriptSerializer()
Dim dict = jss.Deserialize(Of Rootobject)(MyJSON)
MsgBox(dict.results.FirstOrDefault().state_name)
Same, using the Newtonsoft.Json namespace.
The classes properties have being assigned new names, using a <JsonProperty> attribute.
Also, the Results property is modified to return a List(Of Result).
The deserialization is pretty simple and straightforward:
You can use the Visual Studio NuGet Package Manager to install Newtonsoft.Json.
Imports Newtonsoft.Json
Dim latlonResults As RootObject = JsonConvert.DeserializeObject(Of RootObject)(JSON)
Dim state As String = latlonResults.Results(0).StateName
or access a property directly while deserializing:
Dim state As String = JsonConvert.DeserializeObject(Of RootObject)(JSON).Results(0).StateName
Refactored classes:
Public Class RootObject
<JsonProperty("input")>
Public Property Input() As Input
<JsonProperty("results")>
Public Property Results() As List(Of Result)
End Class
Public Class Input
<JsonProperty("lat")>
Public Property Lat() As Double
<JsonProperty("lon")>
Public Property Lon() As Double
End Class
Public Class Result
<JsonProperty("block_fips")>
Public Property BlockFips() As String
<JsonProperty("bbox")>
Public Property Bbox() As List(Of Double)
<JsonProperty("county_fips")>
Public Property CountyFips() As Long
<JsonProperty("county_name")>
Public Property CountyName() As String
<JsonProperty("state_fips")>
Public Property StateFips() As Long
<JsonProperty("state_code")>
Public Property StateCode() As String
<JsonProperty("state_name")>
Public Property StateName() As String
<JsonProperty("block_pop_2015")>
Public Property BlockPop2015() As Long
<JsonProperty("amt")>
Public Property Amt() As String
<JsonProperty("bea")>
Public Property Bea() As String
<JsonProperty("bta")>
Public Property Bta() As String
<JsonProperty("cma")>
Public Property Cma() As String
<JsonProperty("eag")>
Public Property Eag() As String
<JsonProperty("ivm")>
Public Property Ivm() As String
<JsonProperty("mea")>
Public Property Mea() As String
<JsonProperty("mta")>
Public Property Mta() As String
<JsonProperty("pea")>
Public Property Pea() As String
<JsonProperty("rea")>
Public Property Rea() As String
<JsonProperty("rpc")>
Public Property Rpc() As String
<JsonProperty("vpc")>
Public Property Vpc() As String
End Class