Parsing Data from JSON web service vb.net - json

I am having a bit of an issue getting the various types of nested data from a 3rd party API.
I am calling a web service and getting the json stream back, but I can't seem to serialize the data effectively.
I can get the datastream to load into my jobject, but as the structure has an integer that keeps changing I can't just refer to the path.
Dim json As String = reader.ReadToEnd
Dim o As JObject = JObject.Parse(json)
Try
'oForm.AppendtoLogFile("jSON: " & o.Item("tickets").ToString)
oForm.AppendtoLogFile("_____________")
Dim results As List(Of JToken) = o.Children.ToList
For Each item As JProperty In results
oForm.AppendtoLogFile("Item name: " & item.Name.ToString)
Select Case item.Name
Case "tickets"
'next value here is random integer, then array of items
Dim sbase = item.Value.ToString
'oForm.AppendtoLogFile("Tickets: item.value.tostring " & sbase)
item.CreateReader()
If item.Value.Type = JTokenType.Array Then
Dim results2 As List(Of JToken) = item.Value.ToList
For Each subitem As JObject In results2
Dim results3 As List(Of JToken) = subitem.Children().ToList
For Each temp2 As JProperty In results3
temp2.CreateReader()
MsgBox(temp2.Name)
MsgBox(temp2.Value)
Next
Next
End If
End Select
Next
I can dump all the values of the "tickets" section to text file, but each ticket has an integer before another lot of data. Sample json below. Note the 279 value is for each ticket in the stream.
{
"page": 1,
"per_page": 25,
"total": 1,
"cache_id": 1115,
"tickets": {
"279": {
"id": 279,
"ref": "FLUB-xxxx-xxxx",
"auth": "G4xxxxXX",
"sent_to_address": "",
"email_account_address": "",
"creation_system": "web.api",
"creation_system_option": "",
"ticket_hash": "none",
"status": "awaiting_agent",
"hidden_status": null,
"validating": null,
"is_hold": false,
"urgency": 1,
"count_agent_replies": 0,
"count_user_replies": 1,
"feedback_rating": null,
"date_feedback_rating": null,
"date_feedback_rating_ts": 0,
"date_feedback_rating_ts_ms": 0,
"date_created": "2016-07-16 01:54:40",
"date_created_ts": 1468634080,
"date_created_ts_ms": 1468634080000,
"date_resolved": null,
"date_resolved_ts": 0,
"date_resolved_ts_ms": 0,
"date_archived": null,
"date_archived_ts": 0,
"date_archived_ts_ms": 0,
"date_first_agent_assign": "2016-07-16 01:56:12",
"date_first_agent_assign_ts": 1468634172,
"date_first_agent_assign_ts_ms": 1468634172000,
"date_first_agent_reply": null,
"date_first_agent_reply_ts": 0,
"date_first_agent_reply_ts_ms": 0,
"date_last_agent_reply": null,
"date_last_agent_reply_ts": 0,
"date_last_agent_reply_ts_ms": 0,
"date_last_user_reply": "2016-07-16 01:54:41",
"date_last_user_reply_ts": 1468634081,
"date_last_user_reply_ts_ms": 1468634081000,
"date_agent_waiting": null,
"date_agent_waiting_ts": 0,
"date_agent_waiting_ts_ms": 0,
"date_user_waiting": "2016-07-16 01:54:40",
"date_user_waiting_ts": 1468634080,
"date_user_waiting_ts_ms": 1468634080000,
"date_status": "2016-07-16 01:54:40",
"date_status_ts": 1468634080,
"date_status_ts_ms": 1468634080000,
"total_user_waiting": 0,
"total_to_first_reply": 0,
"date_locked": null,
"date_locked_ts": 0,
"date_locked_ts_ms": 0,
"has_attachments": true,
"subject": "test more than 1 attach",
"original_subject": "test more than 1 attach",
-- rest removed for clarity
I am wanting to load each ticket section into a data grid, but need to be able to get data first
the code tries to find values in each sub section, but not really used JSON before and having issues
Would love some ideas.
Thanks
---update---
I have created my classes
Public Class Example
Public Property page As Integer
Public Property per_page As Integer
Public Property total As Integer
Public Property cache_id As Integer
Public Property tickets As Dictionary(Of Integer, tickets)
End Class
and my tickets class. After a bit of mucking around changing values, i can get my data into the deserialzeobject but can't get examples from the Tickets Dictionary.
-----Final Code --------- that works for me
Dim jsonsettings = New JsonSerializerSettings
jsonsettings.NullValueHandling = NullValueHandling.Ignore
jsonsettings.MissingMemberHandling = MissingMemberHandling.Ignore
Try
Dim results As Example = JsonConvert.DeserializeObject(Of Example)(jsonResponseURL, jsonsettings)
Try
For Each s In results.tickets.Values
AppendtoLogFile("Subject: " & s.subject)
Next
'get all ticket subject lines. Loop through dictionary.
Catch ex As Exception
AppendtoLogFile("Error: " & ex.Message)
End Try

You should use a Dictionary( Of Int, Ticket) for your Tickets data. Take your JSON string, and use a service like jsonutils.com to generate your VB.Net classes from your JSON string. It will likely give an invalid type for the Int base Json keys (which are your individual Ticket objects) like shown below.
Public Class Tickets
Public Property 279 As 279
End Class
Public Class Example
Public Property page As Integer
Public Property per_page As Integer
Public Property total As Integer
Public Property cache_id As Integer
Public Property tickets As Tickets
End Class
So take this generated code, delete the Tickets class it generates, rename the 279 class name to Ticket, and finally change the Public Property tickets As Tickets to Public Property tickets As Dictionary( Of Int, Ticket )
Use something like Newtonsoft JSON.Net to deserialize your JSON into your class instances neatly.
I took your partial JSON, and generate the VB.Net classes and fixed the Ticket object as shown below. What I did Something like this should work.
Public Class Example
Public Property page As Integer
Public Property per_page As Integer
Public Property total As Integer
Public Property cache_id As Integer
Public Property tickets As Dictionary( Of Int, Ticket )
End Class
Public Class Ticket
Public Property id As Integer
Public Property ref As String
Public Property auth As String
Public Property sent_to_address As String
Public Property email_account_address As String
Public Property creation_system As String
Public Property creation_system_option As String
Public Property ticket_hash As String
Public Property status As String
Public Property hidden_status As Object
Public Property validating As Object
Public Property is_hold As Boolean
Public Property urgency As Integer
Public Property count_agent_replies As Integer
Public Property count_user_replies As Integer
Public Property feedback_rating As Object
Public Property date_feedback_rating As Object
Public Property date_feedback_rating_ts As Integer
Public Property date_feedback_rating_ts_ms As Integer
Public Property date_created As String
Public Property date_created_ts As Integer
Public Property date_created_ts_ms As Long
Public Property date_resolved As Object
Public Property date_resolved_ts As Integer
Public Property date_resolved_ts_ms As Integer
Public Property date_archived As Object
Public Property date_archived_ts As Integer
Public Property date_archived_ts_ms As Integer
Public Property date_first_agent_assign As String
Public Property date_first_agent_assign_ts As Integer
Public Property date_first_agent_assign_ts_ms As Long
Public Property date_first_agent_reply As Object
Public Property date_first_agent_reply_ts As Integer
Public Property date_first_agent_reply_ts_ms As Integer
Public Property date_last_agent_reply As Object
Public Property date_last_agent_reply_ts As Integer
Public Property date_last_agent_reply_ts_ms As Integer
Public Property date_last_user_reply As String
Public Property date_last_user_reply_ts As Integer
Public Property date_last_user_reply_ts_ms As Long
Public Property date_agent_waiting As Object
Public Property date_agent_waiting_ts As Integer
Public Property date_agent_waiting_ts_ms As Integer
Public Property date_user_waiting As String
Public Property date_user_waiting_ts As Integer
Public Property date_user_waiting_ts_ms As Long
Public Property date_status As String
Public Property date_status_ts As Integer
Public Property date_status_ts_ms As Long
Public Property total_user_waiting As Integer
Public Property total_to_first_reply As Integer
Public Property date_locked As Object
Public Property date_locked_ts As Integer
Public Property date_locked_ts_ms As Integer
Public Property has_attachments As Boolean
Public Property subject As String
Public Property original_subject As String
End Class

Related

Is it okay to do the next class?

Deserialization throws me an exception in the part
Path 'access', line 1, position 10.
I have part of the code like this
Dim lstPyp As List(Of access) = Nothing
lstPyp = JsonConvert.DeserializeObject(Of List(Of access))(strRespuesta)
The json is this
{
"access": "granted",
"last_login": "2022-04-07 10:30:07",
"last_access": "2022-04-07 11:55:01",
"uid": 5497,
"user": "pepe",
"id_comitente": 30,
"profile": "comitente"
}
I have the class as follows
Public Class access
Public Property access As String
Public Property lastlogin As Date
Public Property lastaccess As Date
Public Property uid As Integer
Public Property user As String
Public Property idcomitente As Integer
Public Property profile As String
end class
It is the first time that I have to do the classes.
you don' t have any list, just one object so try this
Dim pyp As access = JsonConvert.DeserializeObject(Of access)(strRespuesta)

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

Deserialize this json in VB.NET

I have this json response:
{
"tracked_until": "1483704963",
"solo_competitive_rank": "4066",
"competitive_rank": "3821",
"mmr_estimate": {
"estimate": 3971,
"stdDev": 215.26495302301302,
"n": 20
},
"profile": {
"account_id": 131505839,
"personaname": "LeG",
"name": null,
"cheese": 1,
"steamid": "76561198091771567",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c0/c09ca9b316ff7bf7dccba6f5a32aba97b8dba05c.jpg",
"avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c0/c09ca9b316ff7bf7dccba6f5a32aba97b8dba05c_medium.jpg",
"avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c0/c09ca9b316ff7bf7dccba6f5a32aba97b8dba05c_full.jpg",
"profileurl": "http://steamcommunity.com/id/LegLabs/",
"last_login": "2016-11-11T13:13:18.651Z",
"loccountrycode": "AL"
}
}
Using an Online Tool, I created these classes:
<Serializable>
Public Class mmr_estimate
Public Property estimate As String
Public Property stdDev As String
Public Property n As String
End Class
<Serializable>
Public Class profile
Public Property account_id As String
Public Property personaname As String
Public Property name As String
Public Property cheese As String
Public Property steamid As String
Public Property avatar As String
Public Property avatarmedium As String
Public Property avatarfull As String
Public Property profileurl As String
Public Property last_login As String
Public Property loccountrycode As String
End Class
<Serializable>
Public Class RootObject
Public Property tracked_until As String
Public Property solo_competitive_rank As String
Public Property competitive_rank As String
Public Property mmr_estimate As mmr_estimate
Public Property profile As profile
End Class
Then I use this code to deserialize it:
Dim steamData As String = ' the json contents above
Dim myjss As New JavaScriptSerializer()
Dim playerDictionary = myjss.Deserialize(Of List(Of RootObject))(steamData)
But the result I get is nothing, playerDictionary has 0 items, when it should have 1 item with the contents of the json parsed into KeyValuePairs.
If I use this piece of code
Dim data = myjss.DeserializeObject(steamData)
and then run a for each loop on the data elements, I can see the contents of data when debugging, but I don't know how to work with them like that, since they are just objects which I'm having trouble converting into KeyValuePairs, who in themselves may contain arrays of KeyValuePairs.
What I'm trying to get is the values of solo_competitive_rank, competitive_rank and steamid, but if I can't get the whole contents deserialized, I can't do that.
Are the declared classes wrong?
but with this solution you use not the class RootObject.
With first method, your JSON want in the list with key and value.
This is only for JSON Array. :(
rg

JSON.NET Deserializing with VB.NET with a value of 'stop'

I am in the process of deserializing a JSON string with VB.NET. I am using JSON.NET and have made a custom class to use with JsonConvert.DeserializeObject function. The only issue I have is one of the values coming through the JSON string is called 'stop'. This causes the VB.NET to not compile, owing to the fact you cannot declare a value with the name 'stop'. When I change the value of 'stop' to something else, the data from the 'stop' value is no longer read from the JSON string. I have been trying to work out how to get around this, but short of changing the JSON string response, which I unfortunately cannot do, I have come up short. Any help would be most appreciated.
Public Class GuideEntry
Public Property eventId As Integer
Public Property episodeId As Integer
Public Property serieslinkId As Integer
Public Property serieslinkUri As String
Public Property channelName As String
Public Property channelUuid As String
Public Property channelNumber As String
Public Property start As Integer
Public Property stop As Integer 'JSON value causing the problem
Public Property title As String
Public Property description As String
Public Property genre As Integer()
Public Property nextEventId As Integer
Public Property episodeUri As String
Public Property episodeNumber As Integer
Public Property episodeOnscreen As String
Public Property subtitle As String
Public Property partNumber As Integer
Public Property partCount As Integer
Public Property starRating As Integer
End Class
Change the name of your stop property
<JsonProperty("stop")> _
Public Property anythingButStop As String
Adding to Arthurs' answer,
VB Code would be something like this.
Public Class GuideEntry
Public Property eventId As Integer
Public Property episodeId As Integer
Public Property serieslinkId As Integer
Public Property serieslinkUri As String
Public Property channelName As String
Public Property channelUuid As String
Public Property channelNumber As String
Public Property start As Integer
<JsonProperty("stop")> _
Public Property stopValue As Integer 'JSON value causing the problem
Public Property title As String
Public Property description As String
Public Property genre As Integer()
Public Property nextEventId As Integer
Public Property episodeUri As String
Public Property episodeNumber As Integer
Public Property episodeOnscreen As String
Public Property subtitle As String
Public Property partNumber As Integer
Public Property partCount As Integer
Public Property starRating As Integer
End Class
Here is .net fiddle link

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.