How do you parse this JSON data? - json

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

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!!

How to define a property as optional

I have the following class
Private Class OCOOrderRecord
Public Property orderListId As Integer
Public Property contingencyType As String
Public Property listStatusType As String
Public Property listOrderStatus As String
Public Property listClientOrderId As String
Public Property transactionTime As Long
Public Property symbol As String
Public Property orders As List(Of OrdersRecord)
Public Property orderReports As List(Of OrderReportsRecord)
End Class
Private Class OrdersRecord
Public Property symbol As String
Public Property orderId As Integer
Public Property clientOrderId As String
End Class
Private Class OrderReportsRecord
Public Property symbol As String
Public Property orderId As Integer
Public Property orderListId As Integer
Public Property clientOrderId As String
Public Property transactTime As Long
Public Property price As String
Public Property origQty As String
Public Property executedQty As String
Public Property cummulativeQuoteQty As String
Public Property status As String
Public Property timeInForce As String
Public Property type As String
Public Property side As String
Public Property stopPrice As String
End Class
The JSON response that I receive has two items in orderReports property. The first one contains a stopPrice value but the second one no. So I fail to parse it correctly. Any help will be appreciated.
I did it by editing the response and adding an empty value for stopPrice property

Deserialize json array to vb .NET object exception - Cannot serialize into because type requires array

I am following the guidelines for deserializing my array but can't figure out why I keep getting this exception. I have also tried this with a non-empty json string unlike the one below.
Private Class lobbActivity
Public Property billNum_List() As String
Public Property ruleOrReg_List() As String
Public Property ratemaking_List() As String
Public Property PcontrNum_List() As String
Public Property Ptitle_List() As String
Public Property MuniOrd_List() As String
Public Property MuniRed_List() As String
Public Property ExOrders_List() As String
Public Property TribeSub_List() As String
Public Property Tribes_List() As String
End Class
Function JSONCreateLobbyist(ByVal activityArr As String)
Dim item = Newtonsoft.Json.JsonConvert.DeserializeObject(Of lobbActivity())(activityArr)
exception
{"billNum_List":["aa","aa"],"ruleOrReg_List":["vbb","vbb"],"ratemaking_List":["bb","bb"],"PcontrNum_List":[],"Ptitle_List":[],"MuniOrd_List":[],"MuniRed_List":[],"ExOrders_List":[],"TribeSub_List":[],"Tribes_List":[]}
Ended up using different syntax that worked
Dim act As lobbActivity = js.Deserialize(Of lobbActivity)(activityArr)
If you are using the Paste as JSON feature in Visual Studio, it does not define array properties correctly.
Private Class lobbActivity
Public Property billNum_List As String()
Public Property ruleOrReg_List As String()
Public Property ratemaking_List As String()
Public Property PcontrNum_List As String()
Public Property Ptitle_List As String()
Public Property MuniOrd_List As String()
Public Property MuniRed_List As String()
Public Property ExOrders_List As String()
Public Property TribeSub_List As String()
Public Property Tribes_List As String()
End Class
Your properties are not arrays they are strings. Use the following modified class
Private Class lobbActivity
Public Property billNum_List() As String()
Public Property ruleOrReg_List() As String()
Public Property ratemaking_List() As String()
Public Property PcontrNum_List() As String()
Public Property Ptitle_List() As String()
Public Property MuniOrd_List() As String()
Public Property MuniRed_List() As String()
Public Property ExOrders_List() As String()
Public Property TribeSub_List() As String()
Public Property Tribes_List() As String()
End Class

Deserialized JSON data returning properties of "Nothing" in VB.NET

This has been driving me mad for the past few days. I am connecting to the Shopify API and downloading JSON data. I have been able to successfully deserialize the data to an object using the class and code below. However, the object "customer" comes back with properties (as per the class) equal to "Nothing". What is going on? Any help would be greatly appreciated!! P.S. I should mention I am using Newtonsoft JSON.NET.
Partial Public Class ParsedJSON
Public Class Customer2
Public Property accepts_marketing As Boolean
Public Property created_at As DateTime
Public Property email As String
Public Property first_name As String
Public Property id As Integer
Public Property last_name As String
Public Property last_order_id As Integer
Public Property multipass_identifier As Object
Public Property note As Object
Public Property orders_count As Integer
Public Property state As String
Public Property total_spent As String
Public Property updated_at As DateTime
Public Property verified_email As Boolean
Public Property tags As String
Public Property last_order_name As String
Public Property default_address As DefaultAddress
End Class
End Class
Partial Public Class ParsedJSON
Public Class Order
Public Property buyer_accepts_marketing As Boolean
Public Property cancel_reason As Object
Public Property cancelled_at As Object
Public Property cart_token As String
Public Property checkout_token As String
Public Property closed_at As Object
Public Property confirmed As Boolean
Public Property created_at As DateTime
Public Property currency As String
Public Property email As String
Public Property financial_status As String
Public Property fulfillment_status As Object
Public Property gateway As String
Public Property id As Integer
Public Property landing_site As String
Public Property location_id As Object
Public Property name As String
Public Property note As String
Public Property number As Integer
Public Property reference As Object
Public Property referring_site As String
Public Property source As String
Public Property source_identifier As Object
Public Property source_name As String
Public Property source_url As Object
Public Property subtotal_price As String
Public Property taxes_included As Boolean
Public Property test As Boolean
Public Property token As String
Public Property total_discounts As String
Public Property total_line_items_price As String
Public Property total_price As String
Public Property total_price_usd As String
Public Property total_tax As String
Public Property total_weight As Integer
Public Property updated_at As DateTime
Public Property user_id As Object
Public Property browser_ip As Object
Public Property landing_site_ref As Object
Public Property order_number As Integer
Public Property discount_codes As Object()
Public Property note_attributes As Object()
Public Property processing_method As String
Public Property checkout_id As Integer
Public Property tax_lines As TaxLine()
Public Property tags As String
Public Property line_items As LineItem()
Public Property shipping_lines As ShippingLine()
Public Property billing_address As BillingAddress
Public Property shipping_address As ShippingAddress
Public Property fulfillments As Object()
Public Property client_details As ClientDetails
Public Property customer As Customer2
End Class
End Class
Partial Public Class ParsedJSON
Public Property orders As Order()
End Class
... You get the idea
Now, here is my implementation code:
' Calls the method GetResponseStream to return the stream associated with the response.
Dim receiveStream As Stream = response.GetResponseStream()
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
' Pipes the response stream to a higher level stream reader with the required encoding format.
Dim readStream As New StreamReader(receiveStream, encode)
Dim json_data As String = readStream.ReadToEnd()
Dim serializer As New JavaScriptSerializer()
Dim customer As ParsedJSON.Customer2 = JsonConvert.DeserializeObject(Of ParsedJSON.Customer2)(json_data)
An example of the JSON data can be seen at http://docs.shopify.com/api/order.
Code defensively. It is a well known issue that Shopify can provide Orders via the API that have null customer records. If you run into one of those, provide some safe defaults. Webhooks can receive orders with null customers too.
And when you fix your problem that bums out with valid customers, all will be well for you.