I was using JSON Utils to generate a Class and I came to a problem. The JSON string I'm using:
{
"type": "champion",
"version": "7.16.1",
"data": {
"1": {
"title": "the Dark Child",
"id": 1,
"key": "Annie",
"name": "Annie"
}
}
}
The Class it generates:
Public Class 1
Public Property title As String
Public Property id As Integer
Public Property key As String
Public Property name As String
End Class
Public Class Data
Public Property 1 As 1
End Class
Public Class Example
Public Property type As String
Public Property version As String
Public Property data As Data
End Class
The thing is that I cannot name a Class 1, I am still trying to find a solution but with no luck yet. Is there a work around this?
I think it should be change to Dictionary
Public Class Example
Public Property type As String
Public Property version As String
Public Property data As Dictionary(Of String, NumberType)
End Class
Public Class NumberType
Public Property title As String
Public Property id As Integer
Public Property key As String
Public Property name As String
End Class
Related
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
I have JSON data from a Fronius solar inverter. I'm trying to read it into VB.NET classes so I can then work some other magic on it (add to a DB, use the info to control household devices etc).
I've parsed the JSON through some online resource that all say it's ok.
When running my code the classes are coming back as nothing.
Here's the base code for deserializing:
Dim fileReader As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader("C:\Temp\JsonCrap.js")
Dim jsonData As String = fileReader.ReadToEnd
fileReader.Close()
Dim myJs = JsonConvert.DeserializeObject(Of Body)(jsonData)
When I expand myJS, it shows the data properties from my class but with no values.
JSON is this:
{
"Body" : {
"Data" : {
"DAY_PMAX" : {
"Unit" : "W",
"Value" : 2013
},
"DAY_UACMAX" : {
"Unit" : "V",
"Value" : 244.80000000000001
},
"DAY_UDCMAX" : {
"Unit" : "V",
"Value" : 375.19999999999999
},
"TOTAL_PMAX" : {
"Unit" : "W",
"Value" : 5568
},
"TOTAL_UACMAX" : {
"Unit" : "V",
"Value" : 285.5
},
"TOTAL_UDCMAX" : {
"Unit" : "V",
"Value" : 389.19999999999999
},
"YEAR_PMAX" : {
"Unit" : "W",
"Value" : 5562
},
"YEAR_UACMAX" : {
"Unit" : "V",
"Value" : 277.30000000000001
},
"YEAR_UDCMAX" : {
"Unit" : "V",
"Value" : 375.19999999999999
}
}
},
"Head" : {
"RequestArguments" : {
"DataCollection" : "MinMaxInverterData",
"DeviceClass" : "Inverter",
"DeviceId" : "1",
"Scope" : "Device"
},
"Status" : {
"Code" : 0,
"Reason" : "",
"UserMessage" : ""
},
"Timestamp" : "2021-07-22T11:34:44+10:00"
}
}
And classes are here:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Serialization
Public Class Body
<JsonProperty(PropertyName:="Body")>
Public Property Data As Data
End Class
Public Class Data
<JsonProperty(PropertyName:="DAY_PMAX")>
Public Property DAY_PMAX As DAYPMAX
<JsonProperty(PropertyName:="DAY_UACMAX")>
Public Property DAY_UACMAX As DAYUACMAX
<JsonProperty(PropertyName:="DAY_UDCMAX")>
Public Property DAY_UDCMAX As DAYUDCMAX
<JsonProperty(PropertyName:="TOTAL_PMAX")>
Public Property TOTAL_PMAX As TOTALPMAX
<JsonProperty(PropertyName:="TOTAL_UACMAX")>
Public Property TOTAL_UACMAX As TOTALUACMAX
<JsonProperty(PropertyName:="TOTAL_UDCMAX")>
Public Property TOTAL_UDCMAX As TOTALUDCMAX
<JsonProperty(PropertyName:="YEAR_PMAX")>
Public Property YEAR_PMAX As YEARPMAX
<JsonProperty(PropertyName:="YEAR_UACMAX")>
Public Property YEAR_UACMAX As YEARUACMAX
<JsonProperty(PropertyName:="YEAR_UDCMAX")>
Public Property YEAR_UDCMAX As YEARUDCMAX
End Class
Public Class DAYPMAX
Public Property Unit As String
Public Property Value As Integer
End Class
Public Class DAYUACMAX
Public Property Unit As String
Public Property Value As Double
End Class
Public Class DAYUDCMAX
Public Property Unit As String
Public Property Value As Double
End Class
Public Class TOTALPMAX
Public Property Unit As String
Public Property Value As Integer
End Class
Public Class TOTALUACMAX
Public Property Unit As String
Public Property Value As Double
End Class
Public Class TOTALUDCMAX
Public Property Unit As String
Public Property Value As Double
End Class
Public Class YEARPMAX
Public Property Unit As String
Public Property Value As Integer
End Class
Public Class YEARUACMAX
Public Property Unit As String
Public Property Value As Double
End Class
Public Class YEARUDCMAX
Public Property Unit As String
Public Property Value As Double
End Class
Public Class RequestArguments
Public Property DataCollection As String
Public Property DeviceClass As String
Public Property DeviceId As String
Public Property Scope As String
End Class
Public Class Status
Public Property Code As Integer
Public Property Reason As String
Public Property UserMessage As String
End Class
Public Class Head
Public Property RequestArguments As RequestArguments
Public Property Status As Status
Public Property Timestamp As DateTime
End Class
Public Class Example
Public Property Body As Body
Public Property Head As Head
End Class
Your class model is missing the Root object. You can see it if you simplify the JSON structure: Body and Head are contained in an Object (hence, both are properties of the same Root object).
{
"Body" : {
},
"Head" : {
}
}
Add a Root object that contains these properties:
Public Class FroniusAPIRoot
Public Property Body As Body
Public Property Head As Head
End Class
I suggest to simplify the model: all those properties of the Data class are just one object Type and the JSON object property name is the Key to get the related object.
You can simply use a Dictionary(Of String, Class) to handle all the Properties of Data.
It's also more flexible, in case those properties can change or the API can return more/different objects, depending on the type of the query.
Partial Public Class Body
Public Property Data As Dictionary(Of String, UnitValues)
End Class
Public Class UnitValues
Public Property Unit As String
Public Property Value As Double
End Class
Use the FroniusAPIRoot class deserialize your JSON:
Dim json = File.ReadAllText("C:\Temp\JsonCrap.js")
Dim froniusData = JsonConvert.DeserializeObject(Of FroniusAPIRoot)(json)
Modified class model:
Note: I'm not sure whether RequestArguments.DeviceId should be interpreted as a string or an integer value. It's defined as string in the JSON. Modify as required (Integer, Long).
If you don't like the Dictionary, add back the Data class and all its properties, but use the UnitValues class to define the Type (since all can use the same Type).
Public Class FroniusAPIRoot
Public Property Body As Body
Public Property Head As Head
End Class
Public Class Body
Public Property Data As Dictionary(Of String, UnitValues)
End Class
Public Class UnitValues
Public Property Unit As String
Public Property Value As Double
End Class
Public Class Head
Public Property RequestArguments As RequestArguments
Public Property Status As Status
Public Property Timestamp As DateTimeOffset
End Class
Public Class RequestArguments
Public Property DataCollection As String
Public Property DeviceClass As String
Public Property DeviceId As String
Public Property Scope As String
End Class
Public Class Status
Public Property Code As Long
Public Property Reason As String
Public Property UserMessage As String
End Class
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
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
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.