Deserialize multilevel JSON string with vb.net - json

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

Related

VB.NET Deserialize JSON with Newton

I'm trying to get to the next level of information from a jSon response.
I can get "code", but I need to get the "result" and some other information that's under "payload".
I don't have a ton of experience with this, so any help would be appreciated!
Here's my code
Dim jason As String = str
Dim parsejson As New JObject
parsejson = JObject.Parse(jason)
Dim theResponseYo As String = parsejson.SelectToken("code").ToString()
MsgBox("You are: " + theResponseYo)
Here's the json I'm parsing:
{
"code": "200",
"status": "success",
"exchange-id": "xxxxxxx",
"payload": {
"transaction": {
"amount": "2.30",
"id": "115340330",
"created": "2022-07-26 20:07:21.157",
"type": "SALE",
"result": "APPROVED",
"card": "XXXXXXXXXXXX1111",
"csc": "999",
"authorization-code": "TAS185",
"batch-string-id": "10",
"display-message": "Transaction approved",
"result-code": "000",
"exp-date": "1222",
"card-type": "VISA",
"sales-tax-amount": "3.00",
"last-four": "1111",
"service-fee": "1.00",
"merchant-id": "12345567",
"terminal-id": "10011111",
"level3": {
"vat-tax-amount": "0.00",
"vat-tax-rate": "0.00",
"order-date": "20220726",
"discount-amount": "0.00",
"destination-country-code": "USA",
"freight-amount": "0.00",
"duty-amount": "0.00",
"level3-items": {
"level3-items": [
{
"item-description": "PRODUCT",
"item-commodity-code": "UPC",
"item-quantity": "1.00",
"item-unit-of-measure": "EA",
"item-product-code": "MATERIAL",
"item-tax-rate": "0.00",
"item-discount": "0.00",
"item-discount-rate": "0.00"
}
]
}
}
},
"payloadType": "transaction"
}
}
There are 2 ways - you can create VB.Net classes and deserialize instead of parsing if you need the most data, or if you need only several values you can do it like this
Dim code As String = parsejson("code").ToString()
Dim code As String = parsejson("payload")("transaction")("result").ToString()
if you want to deserialize
Dim data as Data = JsonConvert.DeserializeObject(Of Data)(jason)
classes
Public Class Data
Public Property code As String
Public Property status As String
Public Property exchange-id As String
Public Property payload As Payload
End Class
Public Class Level3Items
Public Property item-description As String
Public Property item-commodity-code As String
Public Property item-quantity As String
Public Property item-unit-of-measure As String
Public Property item-product-code As String
Public Property item-tax-rate As String
Public Property item-discount As String
Public Property item-discount-rate As String
End Class
Public Class Level3Items
Public Property level3-items As Level3Items()
End Class
Public Class Level3
Public Property vat-tax-amount As String
Public Property vat-tax-rate As String
Public Property order-date As String
Public Property discount-amount As String
Public Property destination-country-code As String
Public Property freight-amount As String
Public Property duty-amount As String
Public Property level3-items As Level3Items
End Class
Public Class Transaction
Public Property amount As String
Public Property id As String
Public Property created As String
Public Property type As String
Public Property result As String
Public Property card As String
Public Property csc As String
Public Property authorization-code As String
Public Property batch-string-id As String
Public Property display-message As String
Public Property result-code As String
Public Property exp-date As String
Public Property card-type As String
Public Property sales-tax-amount As String
Public Property last-four As String
Public Property service-fee As String
Public Property merchant-id As String
Public Property terminal-id As String
Public Property level3 As Level3
End Class
Public Class Payload
Public Property transaction As Transaction
Public Property payloadType As String
End Class

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

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

DataContract Json Serializer and missing bracket in collection of items

When I de-serialize/serialize and data contract to a json format my collection of items is missing the bracket and is causing it fail when posting to web api.
Here is the json in the correct format with [] brackets
{
"basket": {
"basket_platform_type": "in_store",
"basket_currency": {
"currency_id": 2,
"currency_code": "ZAR"
},
"basket_items": [
{
"spaaza_product_id": 18605,
"retailer_product_code": "WBGT0234",
"retailer_item_code": "line_0",
"item_quantity": 3,
"item_price": 250
}
],
"retailer_basket_code": "70401",
"basket_total_price": 750
},
"entity": {
"entity_type": "chain",
"entity_id": 1740,
"branch_business_owner_code": "501",
"branch_business_id": 1341
},
"user": {
"member_programme": "spaaza",
"member_number": "33017307"
}
}
This is what I get, I am missing the [] at basketitems
{
"basket": {
"basket_platform_type": "in_store",
"basket_currency": {
"currency_id": 2,
"currency_code": "ZAR"
},
"basket_items":
{
"spaaza_product_id": 18605,
"retailer_product_code": "WBGT0234",
"retailer_item_code": "line_0",
"item_quantity": 3,
"item_price": 250
},
"retailer_basket_code": "70401",
"basket_total_price": 750
},
"entity": {
"entity_type": "chain",
"entity_id": 1740,
"branch_business_owner_code": "501",
"branch_business_id": 1341
},
"user": {
"member_programme": "spaaza",
"member_number": "33017307"
}
}
Here is classes and the functions I am using for serialization.
Namespace Global.MyPrice
Public Class GetBasketPrice
Public Class Entity
Public Property entity_type As String
Public Property entity_id As Integer
Public Property branch_business_owner_code As String
Public Property branch_business_id As Integer
End Class
Public Class User
Public Property member_programme As String
Public Property member_number As String
End Class
Public Class Basket_Currency
Public Property currency_id As Integer
Public Property currency_code As String
End Class
Public Class Rootobject
Public Property basket As Basket
Public Property entity As Entity
Public Property user As User
End Class
Public Class Basket_Items
Public Property spaaza_product_id As Integer
Public Property retailer_product_code As String
Public Property retailer_item_code As String
Public Property item_quantity As Integer
Public Property item_price As Single
End Class
Public Class Basket
Public Property basket_platform_type As String
Public Property basket_currency As Basket_Currency
Public Property basket_items() As Basket_Items
Public Property retailer_basket_code As String
Public Property basket_total_price As Single
End Class
End Class
End Namespace
This is the serialization function
Dim jsonstring As String
Dim stream1 As New MemoryStream()
Dim ser As New DataContractJsonSerializer(GetType(MyPrice.GetBasketPrice.Rootobject))
ser.WriteObject(stream1, MyPriceBasket)
stream1.Position = 0
Dim sr As New StreamReader(stream1)
Console.Write("JSON form of Person object: ")
jsonstring = sr.ReadToEnd()
Console.WriteLine(jsonstring)
The value for "basket_items" is a JSON array, which is a bracketed list of values: [value1, value2, ..., valueN]. According to the documentation, DataContractJsonSerializer maps "Collections, dictionaries, and arrays" to a JSON array. Thus your basket_items property needs to be a collection of some sort, for instance a List(Of Basket_Items):
Public Class Basket
Public Property basket_platform_type As String
Public Property basket_currency As Basket_Currency
Public Property basket_items As List(Of Basket_Items)
Public Property retailer_basket_code As String
Public Property basket_total_price As Single
End Class
Or, if you want to use an array rather than a list, your () is in the wrong location. You define an array-valued property in VB.NET like this:
Public Property basket_items As Basket_Items()
More here.