Is it okay to do the next class? - json

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)

Related

Deserialize multilevel JSON string with vb.net

I have been trying to deserialize json string in vb.net. I am able successfully get a response using
Using myResp = TryCast(myReq.GetResponse(), System.Net.HttpWebResponse)
Using myReader = New System.IO.StreamReader(myResp.GetResponseStream())
responseContent = myReader.ReadToEnd()
End Using
End Using
responseContent:
{
"devices": {
"totalCount": 1,
"totalPage": 1,
"pageNum": 0,
"transactions": [{
"transactionId": "20211005200111",
"state": "Complete",
"type": "Put",
"operationType": "UPLOAD",
"devices": [{
"imei": "357452100344123",
"code": 40000004,
"message": "DEVICE_INVALID",
"data": "The specified device is not valid."
}, {
"imei": "357452100344409",
"code": 40000005,
"message": "DEVICE_DUPLICATE",
"data": "The specified device already exists."
}]
}]
created classes to hold data:
Public Class devices
Public Property devicelist As List(Of device)
End Class
Public Class device
Public Property pageNum As Integer
Public Property totalCount As Integer
Public Property totalPage As Integer
Public Property transactions As List(Of transaction)
End Class
Public Class transaction
Public Property transactionId As String
Public Property state As String
Public Property type As String
Public Property operationType As String
Public Property devices As List(Of mydevice)
End Class
Public Class mydevice
Public Property imei As String
Public Property code As Integer
Public Property message As String
Public Property data As String
End Class
When I attempt to deserialize, no error is thrown however nothing gets populated:
VB debug
Please let me know what I may be doing wrong?
As for my thoughts,
First of all, it looks like the Json form is wrong.
The last point }} is missing.
Second, Object is wrong.
The property name must be the same as the Json name.
If property name is different, it should be marked using JsonProperty.
I applied the contents and made a test source.
Public Class root
<JsonProperty("devices")>
Public Property devicelist As devices
End Class
Public Class devices
Public Property pageNum As Integer
Public Property totalCount As Integer
Public Property totalPage As Integer
Public Property transactions As List(Of transaction)
End Class
Public Class transaction
Public Property transactionId As String
Public Property state As String
Public Property type As String
Public Property operationType As String
Public Property devices As List(Of mydevice)
End Class
Public Class mydevice
Public Property imei As String
Public Property code As Integer
Public Property message As String
Public Property data As String
End Class
Private Sub test()
Try
Dim Json As String = "{
'devices': {
'totalCount': 1,
'totalPage': 1,
'pageNum': 0,
'transactions': [{
'transactionId': '20211005200111',
'state': 'Complete',
'type': 'Put',
'operationType': 'UPLOAD',
'devices': [{
'imei': '57452100344123',
'code': 40000004,
'message': 'DEVICE_INVALID',
'data': 'The specified device is not valid.'
}, {
'imei': '357452100344409',
'code': 40000005,
'message': 'DEVICE_DUPLICATE',
'data': 'The specified device already exists.'
}]
}]
}}"
Dim ds As root = JsonConvert.DeserializeObject(Of root)(Json)
Dim d As devices = ds.devicelist
Console.WriteLine(d.pageNum)
Console.WriteLine(d.totalCount)
Console.WriteLine(d.totalPage)
For Each tran In d.transactions
Console.WriteLine(tran.transactionId)
For Each dd In tran.devices
Console.WriteLine(dd.code)
Next
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

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

Deserializing multiple objects in json string

I am consuming a web service that is sending multiple objects in a json string.
{ "id": null, "method": "ready", "params": [ { "accept": 1, "serial": "001d50101979" },
{
"result": {
"serial": "001d50101979",
"name": "001d50101979",
"model": "HMP200",
"mode": "normal",
"firmware": {
"version": "3.2.2-1.0.28801",
"status": "normal"
},
"uptime": "233.50",
"bootid": "e62f7839-95b1-4775-8476-c0b1b5b4857f"
},
"error": null,
"id": 1231
} ] }
I am using the following classes
Public Class Firmware
Public Property version As String
Public Property status As String
End Class
Public Class Result
Public Property serial As String
Public Property name As String
Public Property model As String
Public Property mode As String
Public Property firmware As Firmware
Public Property uptime As String
Public Property bootid As String
End Class
Public Class Param
Public Property accept As Integer
Public Property serial As String
End Class
Public Class Player
Public Property id As Object
Public Property method As String
Public Property params As Param()
End Class
I have no issue deserializing the root class Player but I am not sure how to deserialize the class Result.
Dim Player As New Player
Player = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Player)(JsonString)
Dim FirmwareVersion As String = Player.id
Dim bootid As String = Player.method
Dim Model As String = Player.params(0).accept
Dim Serial As String = Player.params.ElementAt(0).serial
Change your class Param to
Public Class Param
Public Property accept As Integer
Public Property serial As String
Public Property result As Result
End Class
then you can access your result like so
Dim Player As New Player
Player = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Player)(JsonString)
Dim FirmwareVersion As String = Player.id
Dim bootid As String = Player.method
Dim Model As String = Player.params(0).accept
Dim Serial As String = Player.params.ElementAt(0).serial
For Each p In Player.params
If p.result IsNot Nothing Then
Console.WriteLine(p.result.model)
End If
Next

Parsing Data from JSON web service vb.net

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