My class is not being populated with the JSON string
Using the VS 2012 Edit -> Paste Special -> JSON as a CLASS
The Class Created:
Public Class clsMCParcelData
Public Class Rootobject
Public Property ParcelFound As Boolean
Public Property ParcelInfo As New APN
End Class
Public Class APN
Public Property Book As String
Public Property Map As String
Public Property Item As String
Public Property clean As String
Public Property formatted As String
Public Property link As String
End Class
END CLASS
JSON String:
{
"ParcelFound":true,
"APN":{
"Book":"510",
"Map":"11",
"Item":"668",
"clean":"51011668",
"formatted":"510-11-668",
"link":"\/api\/parcel\/51011668"
}
}
Code on the asp.vb page:
Dim jss As New JavaScriptSerializer, MCD As New clsMCParcelData.Rootobject
MCD = jss.Deserialize(Of clsMCParcelData.Rootobject)(raw)
I would expect that once deserialized, I would be able to access the APN information like so:
tbParcelNumber.text = MCD.ParcelInfo.formatted (returning 510-11-668)
What I get is Nothing as the value of MCD.ParcelInfo.formatted
The JavaScriptSerializer requires an exact match in the class to deserialize.
Related
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
I have this nested structure
and want to parse it into classes.
I have this code to get the json file and to deserialize it
Public Function getDatasources(ByVal _token As String) As List(Of Results)
Dim client = New RestClient(_baseURI)
Dim request = New RestRequest("/datasource", Method.GET)
request.AddHeader("Authorization", "Bearer " + _token)
request.AddHeader("environment", _environment)
Dim jstr = client.Execute(request).Content
Dim datasourceInfo As List(Of Results) = JsonConvert.DeserializeObject(Of List(Of Results))(jstr)
Return datasourceInfo
End Function
And build this class structure
Public Class Results
Public Property results As List(Of DatasourceInfos)
End Class
Public Class DatasourceInfos
Public Property DSContainer() As List(Of DatasourceInfo)
End Class
Public Class DatasourceInfo
Public Property id As String
Public Property name As String
Public Property description As String
Public Property created As ULong
Public Property modified As ULong
Public Property creator As List(Of Creator)
Public Property editor As List(Of Editor)
End Class
Public Class Creator
Public Property email As String
Public Property login As String
End Class
Public Class Editor
Public Property email As String
Public Property login As String
End Class
But running the code the object datasourceInfo is empty and I do not know why. Anyone who can help me here?
You've mistaken the meaning of the JSON icons. Only square brackets [] denote arrays/lists. The curly brackets {} denote objects.
results is a list of DatasourceInfo (not a list of a list).
DatasourceInfo.creator is a single Creator, and:
DatasourceInfo.editor is a single Editor.
Your code should be changed to:
Public Class Results
Public Property results As List(Of DatasourceInfo)
End Class
Public Class DatasourceInfo
...your other properties...
Public Property creator As Creator
Public Property editor As Editor
End Class
The DatasourceInfos class (note the s on the end) can be removed altogether.
I need to obtain the "title" from the response i get from Youtube.
I get the following error at line 8, position 12, that is, at line:
"items": [
just after the "["
The error i get is:
Exception: Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll ("Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'categoryid.Item' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'items', line 8, position 12."). Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll ("Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'categoryid.Item' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'items', line 8, position 12.") 2.61s [12096] <No Name>
I have this code:
Dim m As IEnumerable(Of Rootobject) = JsonConvert.DeserializeObject(Of IEnumerable(Of Rootobject))(res)
with this JSON data:
{
"kind":"youtube#videoListResponse",
"etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/jznkhy3_Aws9VtommTkcdOYnAAk\"",
"pageInfo":{
"totalResults":1,
"resultsPerPage":1
},
"items":[
{
"kind":"youtube#video",
"etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/M_wQmC4lQBaHJGxo79N7WlmqNr8\"",
"id":"SSbBvKaM6sk",
"snippet":{
"publishedAt":"2009-04-15T20:31:11.000Z",
"channelId":"UC2kTZB_yeYgdAg4wP2tEryA",
"title":"Blur - Song 2",
"description":"Blur 21 -- Celebrating 21 years of Blur. To find out more, click here:http://smarturl.it/blur21y\n\n#blur21\n \nFollow Blur on Twitter:www.twitter.com/blurofficial \nFind Blur on Facebook:www.facebook.com/blur\n\nMusic video by Blur performing Song 2.",
"thumbnails":{
"default":{
"url":"https://i.ytimg.com/vi/SSbBvKaM6sk/default.jpg",
"width":120,
"height":90
},
"medium":{
"url":"https://i.ytimg.com/vi/SSbBvKaM6sk/mqdefault.jpg",
"width":320,
"height":180
},
"high":{
"url":"https://i.ytimg.com/vi/SSbBvKaM6sk/hqdefault.jpg",
"width":480,
"height":360
},
"standard":{
"url":"https://i.ytimg.com/vi/SSbBvKaM6sk/sddefault.jpg",
"width":640,
"height":480
},
"maxres":{
"url":"https://i.ytimg.com/vi/SSbBvKaM6sk/maxresdefault.jpg",
"width":1280,
"height":720
}
},
"channelTitle":"emimusic",
"tags":[
"Blur",
"Song"
],
"categoryId":"10",
"liveBroadcastContent":"none",
"localized":{
"title":"Blur - Song 2",
"description":"Blur 21 -- Celebrating 21 years of Blur. To find out more, click here:http://smarturl.it/blur21y\n\n#blur21\n \nFollow Blur on Twitter:www.twitter.com/blurofficial \nFind Blur on Facebook:www.facebook.com/blur\n\nMusic video by Blur performing Song 2."
}
},
"contentDetails":{
"duration":"PT2M3S",
"dimension":"2d",
"definition":"sd",
"caption":"false",
"licensedContent":true,
"regionRestriction":{
"allowed":[
"BY",
"US"
]
},
"projection":"rectangular"
}
}
]
}
and these classes. the classes are pasted as special with the visual studio 2015 option.
Public Class Rootobject
Public Property kind As String
Public Property etag As String
Public Property pageInfo As Pageinfo
Public Property items() As Item
End Class
Public Class Pageinfo
Public Property totalResults As Integer
Public Property resultsPerPage As Integer
End Class
Public Class Item
Public Property kind As String
Public Property etag As String
Public Property id As String
Public Property snippet As Snippet
Public Property contentDetails As Contentdetails
End Class
Public Class Snippet
Public Property publishedAt As Date
Public Property channelId As String
Public Property title As String
Public Property description As String
Public Property thumbnails As Thumbnails
Public Property channelTitle As String
Public Property tags() As String
Public Property categoryId As String
Public Property liveBroadcastContent As String
Public Property localized As Localized
End Class
Public Class Thumbnails
Public Property _default As _Default
Public Property medium As Medium
Public Property high As High
Public Property standard As Standard
Public Property maxres As Maxres
End Class
Public Class _Default
Public Property url As String
Public Property width As Integer
Public Property height As Integer
End Class
Public Class Medium
Public Property url As String
Public Property width As Integer
Public Property height As Integer
End Class
Public Class High
Public Property url As String
Public Property width As Integer
Public Property height As Integer
End Class
Public Class Standard
Public Property url As String
Public Property width As Integer
Public Property height As Integer
End Class
Public Class Maxres
Public Property url As String
Public Property width As Integer
Public Property height As Integer
End Class
Public Class Localized
Public Property title As String
Public Property description As String
End Class
Public Class Contentdetails
Public Property duration As String
Public Property dimension As String
Public Property definition As String
Public Property caption As String
Public Property licensedContent As Boolean
Public Property regionRestriction As Regionrestriction
Public Property projection As String
End Class
Public Class Regionrestriction
Public Property allowed() As String
End Class
What i need to do?
Thanks in advance.
You are getting that exception because you have declared several auto-implemented array properties incorrectly. As shown in Auto-Implemented Properties (Visual Basic) such properties should be declared as follows, with the () array indicator as part of the return type:
Public Property items As Item()
Instead you declare them as follows:
Public Property items() As Item
This declares a property returning a single Item rather than an array of them. The () attached to the property name is optional; for parameterless properties it is redundant but for properties taking parameters the argument list appears there. See the documentation page Property Statement for details. Then Json.NET throws the exception you see when attempting to deserialize a JSON array into one of the non-array properties in your model.
To fix this, three of your classes should be modified as follows:
Public Class Rootobject
Public Property kind As String
Public Property etag As String
Public Property pageInfo As Pageinfo
Public Property items As Item() ' Fixed
End Class
Public Class Snippet
Public Property publishedAt As Date
Public Property channelId As String
Public Property title As String
Public Property description As String
Public Property thumbnails As Thumbnails
Public Property channelTitle As String
Public Property tags As String() ' Fixed
Public Property categoryId As String
Public Property liveBroadcastContent As String
Public Property localized As Localized
End Class
Public Class Regionrestriction
Public Property allowed As String() ' Fixed
End Class
Then, since the items are an array, to access the titles and put then in a list, you can use extension methods from System.Linq.Enumerable:
' Convert the json string to RootObject.
Dim root = JsonConvert.DeserializeObject(Of Rootobject)(json)
' Extract the list of titles.
Dim titles = root.items _
.Select(Function(i) i.snippet.title) _
.ToList()
' Get the first title in the list.
Dim firstTitle = titles.FirstOrDefault()
Console.WriteLine("First title = ""{0}""", firstTitle)
Which prints out First title = "Blur - Song 2".
Sample VB.Net fiddle.
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
I’m trying to get the results in textures: […] in JSON obtained from
http://t0.rbxcdn.com/ca063a6bab4e145de481384a8a62d64f and display it in a listbox.
I have this code:
Public Class ReturnObject
Public Property Url As String
Public Property textures As String
Public Property obj As String
Public Property mtl As String
Public Property Final As Boolean
End Class
Dim input2 As String = obj.Text
Dim json2 As ReturnObject = JsonConvert.DeserializeObject(Of ReturnObject)(input2)
obj.Text = HttpGet("http://www.roblox.com/thumbnail/resolve-hash/" + json2.obj)
mtl.Text = HttpGet("http://www.roblox.com/thumbnail/resolve-hash/" + json2.mtl)
But I get the error
Error reading string. Unexpected token: StartArray. Path 'textures',
line 1, position 313.
textures is an array in the JSON, containing one string (mind the brackets*):
"textures":["bff5714f0b959385663b1fe030b87064"]
You can reflect that in your class structure (mind the brackets**):
Public Class ReturnObject
Public Property Url As String
Public Property textures As String()
Public Property obj As String
Public Property mtl As String
Public Property Final As Boolean
End Class
* they’re square brackets
** they’re parentheses