How do I use Deserialised JSON Data In VB.Net? - json

I am trying to access data which I think I have successfully deserialized from a JSON file in vb.net.
My program currently reads data into a string from a JSON file. I have been researching how to deserialize the JSON data into a class structure and used a visual studio feature to create the class structure for me.
My question is how do I access this data after it has been deserialized? I have looked through hundreds of pages of forums and stack overflow posts to no avail.
Here is the JSON data:
{
"total": 389097,
"offset": 0,
"items": [
{
"entity": "Play",
"arid": "mpdwyOB32n",
"played_time": "2020-02-21T06:21:26+0000",
"service_id": "triplej",
"recording": {
"entity": "Recording",
"arid": "mtNYq18DdY",
"title": "Supalonely",
"metadata": null,
"description": null,
"duration": 219,
"artists": [
{
"entity": "Artist",
"arid": "ma35vZnl5B",
"name": "Benee",
"artwork": [],
"links": [
{
"entity": "Link",
"arid": "mlb5b4r7A0",
"url": "http://musicbrainz.org/artist/c352c56b-a610-4fc4-884c-704547ef30f5",
"id_component": "c352c56b-a610-4fc4-884c-704547ef30f5",
"title": "MusicBrainz artist",
"mini_synopsis": null,
"short_synopsis": null,
"medium_synopsis": null,
"type": "service",
"provider": "musicbrainz",
"external": true
}
],
"is_australian": null,
"type": "primary",
"role": null
}
],
"releases": [
{
"entity": "Release",
"arid": "mr45LNQePX",
"title": "Stella & Steve",
"format": "EP",
"artwork": [],
"links": [
{
"entity": "Link",
"arid": "mlV0JZbO20",
"url": "http://musicbrainz.org/release-group/9d0271c7-6448-4cbf-a335-0221e34a73ae",
"id_component": "9d0271c7-6448-4cbf-a335-0221e34a73ae",
"title": "MusicBrainz release-group",
"mini_synopsis": null,
"short_synopsis": null,
"medium_synopsis": null,
"type": "service",
"provider": "musicbrainz",
"external": true
}
],
"artists": [
{
"entity": "Artist",
"arid": "ma35vZnl5B",
"name": "Benee",
"artwork": [],
"links": [
{
"entity": "Link",
"arid": "mlb5b4r7A0",
"url": "http://musicbrainz.org/artist/c352c56b-a610-4fc4-884c-704547ef30f5",
"id_component": "c352c56b-a610-4fc4-884c-704547ef30f5",
"title": "MusicBrainz artist",
"mini_synopsis": null,
"short_synopsis": null,
"medium_synopsis": null,
"type": "service",
"provider": "musicbrainz",
"external": true
}
],
"is_australian": null,
"type": "primary",
"role": null
}
],
"record_label": null,
"release_year": null,
"release_album_id": null
}
],
"artwork": [],
"links": [
{
"entity": "Link",
"arid": "mlwkZWz960",
"url": "http://musicbrainz.org/recording/2772cd61-892c-47ab-bc0e-1ca775ebe6f4",
"id_component": "2772cd61-892c-47ab-bc0e-1ca775ebe6f4",
"title": "MusicBrainz recording",
"mini_synopsis": null,
"short_synopsis": null,
"medium_synopsis": null,
"type": "service",
"provider": "musicbrainz",
"external": true
}
]
},
"release": {
"entity": "Release",
"arid": "mr45LNQePX",
"title": "Stella & Steve",
"format": "EP",
"artwork": [],
"links": [
{
"entity": "Link",
"arid": "mlV0JZbO20",
"url": "http://musicbrainz.org/release-group/9d0271c7-6448-4cbf-a335-0221e34a73ae",
"id_component": "9d0271c7-6448-4cbf-a335-0221e34a73ae",
"title": "MusicBrainz release-group",
"mini_synopsis": null,
"short_synopsis": null,
"medium_synopsis": null,
"type": "service",
"provider": "musicbrainz",
"external": true
}
],
"artists": [
{
"entity": "Artist",
"arid": "ma35vZnl5B",
"name": "Benee",
"artwork": [],
"links": [
{
"entity": "Link",
"arid": "mlb5b4r7A0",
"url": "http://musicbrainz.org/artist/c352c56b-a610-4fc4-884c-704547ef30f5",
"id_component": "c352c56b-a610-4fc4-884c-704547ef30f5",
"title": "MusicBrainz artist",
"mini_synopsis": null,
"short_synopsis": null,
"medium_synopsis": null,
"type": "service",
"provider": "musicbrainz",
"external": true
}
],
"is_australian": null,
"type": "primary",
"role": null
}
],
"record_label": null,
"release_year": null,
"release_album_id": null
}
}
]
}
Here is the class structure Visual Studio Generated:
Public Class JSON_Class
Public Class Rootobject
Public Property total As Integer
Public Property offset As Integer
Public Property items() As Item
End Class
Public Class Item
Public Property entity As String
Public Property arid As String
Public Property played_time As Date
Public Property service_id As String
Public Property recording As Recording
Public Property release As Release1
End Class
Public Class Recording
Public Property entity As String
Public Property arid As String
Public Property title As String
Public Property metadata As Object
Public Property description As Object
Public Property duration As Integer
Public Property artists() As Artist
Public Property releases() As Release
Public Property artwork() As Object
Public Property links() As Object
End Class
Public Class Artist
Public Property entity As String
Public Property arid As String
Public Property name As String
Public Property artwork() As Object
Public Property links() As Object
Public Property is_australian As Object
Public Property type As String
Public Property role As Object
End Class
Public Class Release
Public Property entity As String
Public Property arid As String
Public Property title As String
Public Property format As String
Public Property artwork() As Object
Public Property links() As Object
Public Property artists() As Artist1
Public Property record_label As Object
Public Property release_year As Object
Public Property release_album_id As Object
End Class
Public Class Artist1
Public Property entity As String
Public Property arid As String
Public Property name As String
Public Property artwork() As Object
Public Property links() As Object
Public Property is_australian As Object
Public Property type As String
Public Property role As Object
End Class
Public Class Release1
Public Property entity As String
Public Property arid As String
Public Property title As String
Public Property format As String
Public Property artwork() As Object
Public Property links() As Object
Public Property artists() As Artist2
Public Property record_label As Object
Public Property release_year As Object
Public Property release_album_id As Object
End Class
Public Class Artist2
Public Property entity As String
Public Property arid As String
Public Property name As String
Public Property artwork() As Object
Public Property links() As Object
Public Property is_australian As Object
Public Property type As String
Public Property role As Object
End Class
End Class
I deserialize my data using this line: (Where JSON_Class is the class structure and New_JSON_Content is the raw JSON)
Dim JSON_Wrapper = JsonConvert.DeserializeObject(Of JSON_Class)(New_JSON_Content)
What would be my next step if say I wanted to access any one specific variable from the populated class structure? Thanks!

The reason you can't see any data is that JSON_Class, the class you are deserializing to, contains no members. The code works; it's doing exactly what you're telling it to - create an instance of JSON_Class - which contains nothing - from this JSON string. JSON tokens which don't match anything in the deserialization type are ignored, which in this case is everything.
To make this work, deserialize to JSON_Class.Rootobject instead. You also don't need to nest your deserialization classes in a containing class.

Related

Having issues creating proper class for JSON.Net Deserialization of complex object. Receiving {"Cannot deserialize the current JSON array

This is a VB.Net project. Cannot seem to get the class library correct for deserializing the response string to the classes.
Error we receive when we try to deserialize is:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'blahblah_Framework_Root.blahblah+Tokenscopelist'
because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
Sample response trying to deserialize:
{
"data": {
"expiresAt": "2021-11-27T01:12:05.000Z",
"createdAt": "2021-11-13T01:12:05.000Z",
"identityId": 2347335,
"identity": {
"id": 2347335,
"namespace": {
"id": 7760,
"nickname": "org:random-parking"
}
},
"tokenScopeList": [
{
"org": {
"id": 5995,
"name": "RANDOM Parking",
"opal": "opal:prod:helium:alpha:5995:org:5995",
"parentOrg": null,
"packagePlans": [
{
"id": 50,
"package": {
"id": 14,
"name": "Additional Users Over 500",
"packageFeatures": [
{
"config": null,
"id": 147,
"feature": {
"id": 1,
"name": "Users Included",
"code": "users"
}
}
]
},
"isSelected": true
},
{
"id": 54,
"package": {
"id": 15,
"name": "Elevator I/O Boards",
"packageFeatures": [
{
"config": null,
"id": 175,
"feature": {
"id": 21,
"name": "Elevator I/O Boards",
"code": "elevatorIoBoards"
}
}
]
},
"isSelected": true
},
{
"id": 38,
"package": {
"id": 11,
"name": "Premium",
"packageFeatures": [
{
"config": {
"count": 500
},
"id": 91,
"feature": {
"id": 1,
"name": "Users Included",
"code": "users"
}
},
{
"config": {
"count": 1000000
},
"id": 92,
"feature": {
"id": 2,
"name": "Administrators",
"code": "administrators"
}
}
]
},
"isSelected": true
}
]
},
"user": {
"id": 2502299,
"opal": "opal:prod:helium:alpha:5995:user:2502299"
},
"scope": [
"o5995-admin:r",
"o5995-admin:w",
"o5995-configurations:r",
"o5995-configurations:w",
"o5995-dash:r",
"o5995-dash:w",
"o5995-videoProviderPlayback:w"
]
},
{
"org": {
"id": null,
"name": null
},
"user": {
"id": null,
"opal": null
},
"scope": [
"i2347335:r",
"i2347335:w"
]
}
],
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVw"
},
"meta": {
"accessToken": null
}
}
Using this class definition
Public Class RootobjectLogin
Public Property data As DataumLogin
Public Property meta As Meta
End Class
Public Class DataumLogin
Public Property expiresAt As Date
Public Property createdAt As Date
Public Property identityId As Integer
Public Property identity As Identity
Public Property tokenScopeList() As Tokenscopelist
Public Property token As String
End Class
Public Class Tokenscopelist
Public Property org As Org
Public Property user As User
Public Property scope() As String
End Class
Public Class Packageplan
Public Property id As Integer
Public Property package As Package
Public Property isSelected As Boolean
End Class
Public Class Package
Public Property id As Integer
Public Property name As String
Public Property packageFeatures() As New List(Of Packagefeature)
End Class
Public Class Packagefeature
Public Property config As Config
Public Property id As Integer
Public Property feature As Feature
End Class
Public Class Config
Public Property count As Integer
End Class
Public Class Feature
Public Property id As Integer
Public Property name As String
Public Property code As String
End Class
Public Class User
Public Property id As Integer
Public Property opal As String
End Class
Public Class Org
Public Property id As Integer
Public Property name As String
Public Property opal As String
Public Property parentOrg As Object
Public Property packagePlans() As New List(Of Packageplan)
End Class
Public Class Meta
Public Property accessToken As Accesstoken
End Class
Ideas?

Json not derserialising correctly

Json string is not deserialsing correctly
have played around with my classes etc, but bfevent always returns Nothing
have tried Public Property bfevent As BFEvent() in case it needs to be able to take multi values
pretty sure it's something simple....
strcatalogue = "{ "jsonrpc": "2.0", "result": [{ "event": { "id": "29202748", "name": "Kings XI Punjab v Mumbai Indians", "countryCode": "GB", "timezone": "GMT", "openDate": "2019-03-30T10:30:00.000Z" }, "marketCount": 20 }, { "event": { "id": "29201119", "name": "Victoria v NSW Blues", "countryCode": "AU", "timezone": "GMT", "openDate": "2019-03-27T23:30:00.000Z" }, "marketCount": 2 }, { "event": { "id": "29202753", "name": "Chennai Super Kings v Rajasthan Royals", "countryCode": "GB", "timezone": "GMT", "openDate": "2019-03-31T14:30:00.000Z" }, "marketCount": 35 }], "id": 1 }"
Dim objJson = JsonConvert.DeserializeObject(Of BFEventList)(strCatalogue)
Public Class BFEvent
Public Property id As String
Public Property name As String
Public Property countryCode As String
Public Property timezone As String
Public Property openDate As DateTime
End Class
Public Class BFResult
Public Property bfevent As BFEvent
Public Property marketCount As Integer
End Class
Public Class BFEventList
Public Property jsonrpc As String
Public Property result As BFResult()
Public Property id As Integer
End Class
BFEvent = Nothing
marketCount works fine, so something to do with BFEvents class
So i renamed my class to refer to the actual string values in the json. So bfevent is now event. I'm not sure if this is 'required' or not. Will test that elsewhere where i have working code.
But am now getting 'Keyword is not a valid identifier' for
Public Property Event As BFEvent()
with Event underlined.
No errors here
Dim Name As String = objJson.result(0).Event(0).name
But cannot compile due to above error

Iterate a deserealized .Net Object from Json to create a DataTable

I've being spending a lot of time thinking about how to iterate an object from a deserealized json which has many items, subitems and sub-subitems. I know there are a lot of questions already posted, but I still don't get it, 'cause the examples are differrents to mine and I'm a begineer developper. I get the Json from a Web Service and I pass the Token by headers and all that stuff, but I don't know the best way to manipulate this info. I'm using Newtonsoft library, BTW.
The Json is:
{
"orders": [
{
"customer": {
"id": "string",
"externalId": "string",
"firstName": "string",
"lastName": "string",
"name": "string",
"companyName": "string",
"emailAddresses": [
"string"
],
"phones": [
{
"type": "Mobile",
"number": "string"
}
],
"addresses": [
{
"lines": [
"string"
],
"locality": [
"string"
],
"region": "string",
"postcode": "string"
}
]
},
"vehicles": [
{
"id": "string",
"description": "string",
"vin": "string",
"odometer": 0,
"tag": "string",
"nextServiceDue": "2015-07-14T10:08:15Z",
"registrationTestDue": "2015-07-14T10:08:15Z",
"brand": "string",
"extendedWarrantyEndDate": 0,
"contractEndDate": 0,
"transmissionCode": "string",
"engineCode": "string",
"bodyType": "string",
"paintCode": "string",
"modelCode": "string",
"references": [
{
"key": "string",
"value": "string"
}
]
}
],
"employees": [
{
"id": "string",
"name": "string",
"type": "Technician"
}
],
"operations": [
{
"id": "35955",
"code": "RWB",
"externalCode": "RACS",
"description": "431151: Front Shock Absorber Assembly (One Side), Repair/Replace",
"isNew": true,
"labour": {
"pricing": {
"totals": {
"total": 0
}
},
"times": [
{
"quantity": 1.2
}
]
}
}
],
"parts": [
{
"number": "string",
"quantity": 1,
"quantityUnitOfMeasure": "Hour",
"description": "string",
"vehicleId": "string",
"pricing": {
"totals": {
"total": 0
}
}
}
]
}
],
"paging": {
"page": 0,
"morePages": true,
"resultCount": 0,
"pageCount": 0
}
}
And the Code for getting the json properties is:
Public Class Rootobject
Public Property orders() As Order
Public Property paging As Paging
End Class
Public Class Paging
Public Property page As Integer
Public Property morePages As Boolean
Public Property resultCount As Integer
Public Property pageCount As Integer
End Class
Public Class Order
Public Property customer As Customer
Public Property vehicles() As Vehicle
Public Property employees() As Employee
Public Property operations() As Operation
Public Property parts() As Part
End Class
Public Class Customer
Public Property id As String
Public Property externalId As String
Public Property firstName As String
Public Property lastName As String
Public Property name As String
Public Property companyName As String
Public Property emailAddresses() As String
Public Property phones() As Phone
Public Property addresses() As Address
End Class
Public Class Phone
Public Property type As String
Public Property number As String
End Class
Public Class Address
Public Property lines() As String
Public Property locality() As String
Public Property region As String
Public Property postcode As String
End Class
Public Class Vehicle
Public Property id As String
Public Property description As String
Public Property vin As String
Public Property odometer As Integer
Public Property tag As String
Public Property nextServiceDue As Date
Public Property registrationTestDue As Date
Public Property brand As String
Public Property extendedWarrantyEndDate As Integer
Public Property contractEndDate As Integer
Public Property transmissionCode As String
Public Property engineCode As String
Public Property bodyType As String
Public Property paintCode As String
Public Property modelCode As String
Public Property references() As Reference
End Class
Public Class Reference
Public Property key As String
Public Property value As String
End Class
Public Class Employee
Public Property id As String
Public Property name As String
Public Property type As String
End Class
Public Class Operation
Public Property id As String
Public Property code As String
Public Property externalCode As String
Public Property description As String
Public Property isNew As Boolean
Public Property labour As Labour
End Class
Public Class Labour
Public Property pricing As Pricing
Public Property times() As Time
End Class
Public Class Pricing
Public Property totals As Totals
End Class
Public Class Totals
Public Property total As Integer
End Class
Public Class Time
Public Property quantity As Single
End Class
Public Class Part
Public Property number As String
Public Property quantity As Integer
Public Property quantityUnitOfMeasure As String
Public Property description As String
Public Property vehicleId As String
Public Property pricing As Pricing1
End Class
Public Class Pricing1
Public Property totals As Totals1
End Class
Public Class Totals1
Public Property total As Integer
End Class
And I deserealize the Json and i've traying this, an example:
Dim JsonObject As List(Of Rootobject) = JsonConvert.DeserializeObject(Of List(Of Rootobject))(_JsonString)
For Each item In JsonObject
_PagPage = item.paging.page
_PagMorePag = item.paging.morePages
_PagResCount = item.paging.resultCount
_PagPagCount = item.paging.pageCount
Next
I tried to use Lists like List(Of Rootobject) or List(Of List(Of Dictionary(Of Rootoobject)), but it's still not working.
If you could to help me out i'd really appreciate it.

VB.NET deserialize Newtonsoft JSON into object dynamically

ANSWER given describes using LINQ to JSON and the JObject to convert from JSON to a workable object on the fly. Below is the completed code that takes me from my JSON to a workable object, followed by the original question.
'Parse string of JSON data into a JObject that can be accessed via VB.NET
Dim resultSet As JObject = JObject.Parse(responseBody)
'Data can be accessed as seen below
Dim cpu As String = CType(resultSet("KeyName"), String)
=========================================================================
I have a web app that will be making several API calls to a service called inContact (http://www.incontact.com/)
Each of the API calls will be receiving an HTTP response filled with JSON formatted in this way:
{
"resultSet": {
"_links": {
"self": "string",
"next": "string",
"previous": "string"
},
"businessUnitId": 0,
"lastPollTime": "2016-11-08T21:45:46.510Z",
"totalRecords": 0,
"agents": [
{
"agentId": 0,
"userName": "string",
"firstName": "string",
"middleName": "string",
"lastName": "string",
"emailAddress": "string",
"isActive": true,
"teamId": 0,
"teamName": "string",
"reportToId": 0,
"reportToName": "string",
"isSupervisor": true,
"lastLogin": "2016-11-08T21:45:46.510Z",
"lastUpdated": "2016-11-08T21:45:46.510Z",
"location": "string",
"custom1": "string",
"custom2": "string",
"custom3": "string",
"custom4": "string",
"custom5": "string",
"internalId": "string",
"profileId": 0,
"profileName": "string",
"timeZone": "string",
"country": "string",
"countryName": "string",
"state": "string",
"city": "string",
"chatRefusalTimeout": 0,
"phoneRefusalTimeout": 0,
"workItemRefusalTimeout": 0,
"defaultDialingPattern": 0,
"defaultDialingPatternName": "string",
"teamDefaultMaxChats": true,
"maxConcurrentChats": 0,
"notes": "string",
"createDate": "2016-11-08T21:45:46.510Z",
"inactiveDate": "2016-11-08T21:45:46.510Z",
"hireDate": "2016-11-08T21:45:46.510Z",
"terminationDate": "2016-11-08T21:45:46.510Z",
"rehireStatus": true,
"employmentType": 0,
"employmentTypeName": "Full-Time",
"referral": "string",
"atHome": true,
"hiringSource": "string",
"ntLoginName": "string",
"scheduleNotification": "5",
"federatedId": "string",
"sipUser": "string",
"useTeamMaxEmailInboxCount": true,
"maxEmailInboxCount": 0
}
]
}
}
I am deserializing the JSON with Newtonsoft. However, with each different call there will be different key/value pairs, such as this:
{
"resultSet": {
"businessUnitId": 0,
"lastPollTime": "2016-11-08T21:45:46.604Z",
"teams": [
{
"teamId": 0,
"teamName": "string",
"isActive": true,
"description": "string",
"notes": "string",
"lastUpdateTime": "2016-11-08T21:45:46.604Z",
"inViewEnabled": true,
"wfoEnabled": true,
"wfmEnabled": true,
"qmEnabled": true,
"maxConcurrentChats": 0,
"agentCount": 0,
"maxEmailInboxCount": true,
"inViewGamificationEnabled": true,
"inViewChatEnabled": true,
"inViewLMSEnabled": true,
"analyticsEnabled": true
}
],
"agents": [
{
"agentId": 0,
"firstName": "string",
"lastName": "string"
}
]
}
}
I currently am taking in the HTTP response and deserializing the JSON to create a workable .NET object. To do so this is my shortened code, omitting the HTTP request, assuming the request was successful:
If Not String.IsNullOrEmpty(responseBody) Then
' Success. Do something with the response.
'Declare object for holding the JSON from the API call for this call only (class does not fit other calls)
Dim resultSet As GetAgentsAPICall = New GetAgentsAPICall
'Deserialize JSON response into the new resultSet object
resultSet = JsonConvert.DeserializeObject(responseBody)
The issue is that I need a specific class for each API call, instead of just being able to take a string with JSON formatting and throw it into an object with properties matching the key/values. Below is the class I have that takes in just the above API call (the first one listed, longer in length):
Public Class GetAgentsAPICall
Public Property resultSet As Resultset
End Class
Public Class Resultset
Public Property _links As _Links
Public Property businessUnitId As Integer
Public Property lastPollTime As Date
Public Property totalRecords As Integer
Public Property agents() As Agent
End Class
Public Class _Links
Public Property self As String
Public Property _next As String
Public Property previous As String
End Class
Public Class Agent
Public Property agentId As Integer
Public Property userName As String
Public Property firstName As String
Public Property middleName As String
Public Property lastName As String
Public Property emailAddress As String
Public Property isActive As Boolean
Public Property teamId As Integer
Public Property teamName As String
Public Property reportToId As Integer
Public Property reportToName As String
Public Property isSupervisor As Boolean
Public Property lastLogin As Date
Public Property lastUpdated As Date
Public Property location As String
Public Property custom1 As String
Public Property custom2 As String
Public Property custom3 As String
Public Property custom4 As String
Public Property custom5 As String
Public Property internalId As String
Public Property profileId As Integer
Public Property profileName As String
Public Property timeZone As String
Public Property country As String
Public Property countryName As String
Public Property state As String
Public Property city As String
Public Property chatRefusalTimeout As Integer
Public Property phoneRefusalTimeout As Integer
Public Property workItemRefusalTimeout As Integer
Public Property defaultDialingPattern As Integer
Public Property defaultDialingPatternName As String
Public Property teamDefaultMaxChats As Boolean
Public Property maxConcurrentChats As Integer
Public Property notes As String
Public Property createDate As Date
Public Property inactiveDate As Date
Public Property hireDate As Date
Public Property terminationDate As Date
Public Property rehireStatus As Boolean
Public Property employmentType As Integer
Public Property employmentTypeName As String
Public Property referral As String
Public Property atHome As Boolean
Public Property hiringSource As String
Public Property ntLoginName As String
Public Property scheduleNotification As String
Public Property federatedId As String
Public Property sipUser As String
Public Property useTeamMaxEmailInboxCount As Boolean
Public Property maxEmailInboxCount As Integer
End Class
I'm trying to avoid having 20 or 30 similar lengthy classes prebuilt, and instead build a modifiable list or object on the fly. I will need to take the values and either store them in a database or modify them and use another API call to POST the values back. Does anyone have a best practice, or am I stuck with 20-30 huge class definitions?
Thanks for your time!
Parse it with a JObject, which can also be queried using LINQ (see Newtonsoft's LINQ to JSON API, which sits under the Newtonsoft.Json.Linq namespace):
JObject o = JObject.Parse(#"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
The example is in C#, but you can find relevant VB.NET answers on StackOverflow (have a look at the answer here, for example).

VB & Rotten Tomatoes JSON API

I'm trying to allow a user to enter a film title into my program, then have the program return the top three matching films in the rotten tomatoes database.
Here's the code I have so far:
Private Sub Query(ByVal searchTerm As String)
'declare the url, request, response and reader,
Dim url As String
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Console.BackgroundColor = ConsoleColor.Red : Console.WriteLine(" QUERYING ROTTEN TOMATOES FOR THE SEARCHTERM {0} ", searchTerm) : Console.BackgroundColor = ConsoleColor.Black
Try
'base url, query, apikey, page (or result) limit,
url = String.Format("http://api.rottentomatoes.com/api/public/v1.0/movies.json?q={0}&apikey={1}&page_limit={2}", searchTerm, myApiKey, "3")
'make the request
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
'get the response
response = DirectCast(request.GetResponse(), HttpWebResponse)
'read the response
reader = New StreamReader(response.GetResponseStream())
'declare a string for the raw response
Dim rawResponse As String
'get the response a raw string
rawResponse = reader.ReadToEnd()
'write the raw response to the console
Console.WriteLine(rawResponse)
'write that the rest of the data is specific
Console.BackgroundColor = ConsoleColor.Red : Console.WriteLine(" EXTRACTED DATA: ") : Console.BackgroundColor = ConsoleColor.Black
'parse the results from the rawresponse
Dim jResults As JObject = JObject.Parse(rawResponse)
Console.WriteLine(ParseTitle(jResults("total")))
Console.WriteLine(ParseTitle(jResults("title")))
'Console.WriteLine(ParseTitle(jResults("critics_score")))
Catch ex As Exception
Console.WriteLine("Error: " & ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
Console.BackgroundColor = ConsoleColor.Red : Console.WriteLine(" QUERY FINISHED. PRESS ANY KEY TO CLOSE... ") : Console.BackgroundColor = ConsoleColor.Black
Console.ReadKey()
End Sub
I'm using the JSON.Net library, and, truthfully, have no experience with JSON - I've been working of off tutorials.
I'd like to be able to get all the films returned to an array of Movie data structures Can anyone help me out?
Here's the response I get if I search for 'toy story':
{
"total": 7,
"movies": [
{
"id": "770672122",
"title": "Toy Story 3",
"year": 2010,
"mpaa_rating": "G",
"runtime": 103,
"critics_consensus": "Deftlyblending comedy, adventure, and honest emotion, Toy Story 3 is a raresecond sequel that reallyworks.",
"release_dates": {
"theater": "2010-06-18",
"dvd": "2010-11-02"
},
"ratings": {
"critics_rating": "CertifiedFresh",
"critics_score": 99,
"audience_rating": "Upright",
"audience_score": 91
},
"synopsis": "Pixarreturns to their first success with Toy Story 3. The movie begins withAndy leaving for college and donating his beloved toys -- includingWoody (Tom Hanks) and Buzz (Tim Allen) -- to a daycare. While the crewmeets new friends, including Ken (Michael Keaton), they soon grow tohate their new surroundings and plan an escape. The film was directedby Lee Unkrich from a script co-authored by Little Miss Sunshinescribe Michael Arndt. ~ Perry Seibert,Rovi",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/11/13/43/11134356_mob.jpg",
"profile": "http://content6.flixster.com/movie/11/13/43/11134356_pro.jpg",
"detailed": "http://content6.flixster.com/movie/11/13/43/11134356_det.jpg",
"original": "http://content6.flixster.com/movie/11/13/43/11134356_ori.jpg"
},
"abridged_cast": [
{
"name": "TomHanks",
"id": "162655641",
"characters": [
"Woody"
]
},
{
"name": "TimAllen",
"id": "162655909",
"characters": [
"Buzz Lightyear"
]
},
{
"name": "JoanCusack",
"id": "162655020",
"characters": [
"Jessie theCowgirl"
]
},
{
"name": "NedBeatty",
"id": "162672460",
"characters": [
"Lots-o'-Huggin'Bear",
"Lotso"
]
},
{
"name": "DonRickles",
"id": "341817905",
"characters": [
"Mr. PotatoHead"
]
}
],
"alternate_ids": {
"imdb": "0435761"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122.json",
"alternate": "http://www.rottentomatoes.com/m/toy_story_3/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/cast.json",
"clips": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/clips.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json"
}
},
{
"id": "9414",
"title": "ToyStory2",
"year": 1999,
"mpaa_rating": "G",
"runtime": 92,
"critics_consensus": "ToyStory 2 employs inventive storytelling, gorgeous animation, and a topnotch voice cast to deliver another rich moviegoing experience for allages, one that's arguably even better than itspredecessor.",
"release_dates": {
"theater": "1999-11-24",
"dvd": "2000-10-17"
},
"ratings": {
"critics_rating": "CertifiedFresh",
"critics_score": 100,
"audience_rating": "Upright",
"audience_score": 72
},
"synopsis": "",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/10/93/63/10936392_mob.jpg",
"profile": "http://content6.flixster.com/movie/10/93/63/10936392_pro.jpg",
"detailed": "http://content6.flixster.com/movie/10/93/63/10936392_det.jpg",
"original": "http://content6.flixster.com/movie/10/93/63/10936392_ori.jpg"
},
"abridged_cast": [
{
"name": "TomHanks",
"id": "162655641",
"characters": [
"Woody"
]
},
{
"name": "TimAllen",
"id": "162655909",
"characters": [
"Buzz Lightyear"
]
},
{
"name": "JoanCusack",
"id": "162655020",
"characters": [
"Jessie theCowgirl"
]
},
{
"name": "KelseyGrammer",
"id": "162660300",
"characters": [
"Stinky Pete theProspector"
]
},
{
"name": "DonRickles",
"id": "341817905",
"characters": [
"Mr. PotatoHead"
]
}
],
"alternate_ids": {
"imdb": "0120363"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/9414.json",
"alternate": "http://www.rottentomatoes.com/m/toy_story_2/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/9414/cast.json",
"clips": "http://api.rottentomatoes.com/api/public/v1.0/movies/9414/clips.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/9414/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/9414/similar.json"
}
},
{
"id": "9559",
"title": "ToyStory",
"year": 1995,
"mpaa_rating": "G",
"runtime": 80,
"critics_consensus": "Asentertaining as it is innovative, Toy Story kicked off Pixar'sunprecedented run of quality pictures, reinvigorating animated film intheprocess.",
"release_dates": {
"theater": "1995-11-22",
"dvd": "2001-03-20"
},
"ratings": {
"critics_rating": "CertifiedFresh",
"critics_score": 100,
"audience_rating": "Upright",
"audience_score": 81
},
"synopsis": "",
"posters": {
"thumbnail": "http://content7.flixster.com/movie/10/93/63/10936393_mob.jpg",
"profile": "http://content7.flixster.com/movie/10/93/63/10936393_pro.jpg",
"detailed": "http://content7.flixster.com/movie/10/93/63/10936393_det.jpg",
"original": "http://content7.flixster.com/movie/10/93/63/10936393_ori.jpg"
},
"abridged_cast": [
{
"name": "TomHanks",
"id": "162655641",
"characters": [
"Woody"
]
},
{
"name": "TimAllen",
"id": "162655909",
"characters": [
"Buzz Lightyear"
]
},
{
"name": "DonRickles",
"id": "341817905",
"characters": [
"Mr. PotatoHead"
]
},
{
"name": "Jim Varney",
"id": "162662792",
"characters": [
"SlinkyDog"
]
},
{
"name": "WallaceShawn",
"id": "162671862",
"characters": [
"Rex"
]
}
],
"alternate_ids": {
"imdb": "0114709"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/9559.json",
"alternate": "http://www.rottentomatoes.com/m/toy_story/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/9559/cast.json",
"clips": "http://api.rottentomatoes.com/api/public/v1.0/movies/9559/clips.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/9559/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/9559/similar.json"
}
}
],
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=toy+story&page_limit=3&page=1",
"next": "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=toy+story&page_limit=3&page=2"
},
"link_template": "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q={search-term}&page_limit={results-per-page}&page={page-number}"
}
First you need to create classes to receive the JSON data:
Public Class ReleaseDates
Public Property theater As String
Public Property dvd As String
End Class
Public Class Ratings
Public Property critics_rating As String
Public Property critics_score As Integer
Public Property audience_rating As String
Public Property audience_score As Integer
End Class
Public Class Posters
Public Property thumbnail As String
Public Property profile As String
Public Property detailed As String
Public Property original As String
End Class
Public Class AbridgedCast
Public Property name As String
Public Property id As String
Public Property characters As List(Of String)
End Class
Public Class AlternateIds
Public Property imdb As String
End Class
Public Class Links
Public Property self As String
Public Property alternate As String
Public Property cast As String
Public Property clips As String
Public Property reviews As String
Public Property similar As String
End Class
Public Class Movie
Public Property id As String
Public Property title As String
Public Property year As Integer
Public Property mpaa_rating As String
Public Property runtime As Integer
Public Property critics_consensus As String
Public Property release_dates As ReleaseDates
Public Property ratings As Ratings
Public Property synopsis As String
Public Property posters As Posters
Public Property abridged_cast As List(Of AbridgedCast)
Public Property alternate_ids As AlternateIds
Public Property links As Links
End Class
Public Class Links2
Public Property self As String
<JsonProperty(PropertyName:="next")>
Public Property nextItem As String
End Class
Public Class RootObject
Public Property total As Integer
Public Property movies As List(Of Movie)
Public Property links As Links2
Public Property link_template As String
End Class
Once you have done that, you can simply call JsonConvert.DeserializeObject to deserialize your JSON data:
Sub Main()
Dim json As String
json = "{""total"":7,""movies"":[{""id"":""770672122"",""title"":""Toy Story 3"",""year"":2010,""mpaa_rating"":""G"",""runtime"":103,""critics_consensus"":""Deftly blending comedy, adventure, and honest emotion, Toy Story 3 is a rare second sequel that really works."",""release_dates"":{""theater"":""2010-06-18"",""dvd"":""2010-11-02""},""ratings"":{""critics_rating"":""Certified Fresh"",""critics_score"":99,""audience_rating"":""Upright"",""audience_score"":91},""synopsis"":""Pixar returns to their first success with Toy Story 3. The movie begins with Andy leaving for college and donating his beloved toys -- including Woody (Tom Hanks) and Buzz (Tim Allen) -- to a daycare. While the crew meets new friends, including Ken (Michael Keaton), they soon grow to hate their new surroundings and plan an escape. The film was directed by Lee Unkrich from a script co-authored by Little Miss Sunshine scribe Michael Arndt. ~ Perry Seibert, Rovi"",""posters"":{""thumbnail"":""http://content6.flixster.com/movie/11/13/43/11134356_mob.jpg"",""profile"":""http://content6.flixster.com/movie/11/13/43/11134356_pro.jpg"",""detailed"":""http://content6.flixster.com/movie/11/13/43/11134356_det.jpg"",""original"":""http://content6.flixster.com/movie/11/13/43/11134356_ori.jpg""},""abridged_cast"":[{""name"":""Tom Hanks"",""id"":""162655641"",""characters"":[""Woody""]},{""name"":""Tim Allen"",""id"":""162655909"",""characters"":[""Buzz Lightyear""]},{""name"":""Joan Cusack"",""id"":""162655020"",""characters"":[""Jessie the Cowgirl""]},{""name"":""Ned Beatty"",""id"":""162672460"",""characters"":[""Lots-o'-Huggin' Bear"",""Lotso""]},{""name"":""Don Rickles"",""id"":""341817905"",""characters"":[""Mr. Potato Head""]}],""alternate_ids"":{""imdb"":""0435761""},""links"":{""self"":""http://api.rottentomatoes.com/api/public/v1.0/movies/770672122.json"",""alternate"":""http://www.rottentomatoes.com/m/toy_story_3/"",""cast"":""http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/cast.json"",""clips"":""http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/clips.json"",""reviews"":""http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/reviews.json"",""similar"":""http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json""}},{""id"":""9414"",""title"":""Toy Story 2"",""year"":1999,""mpaa_rating"":""G"",""runtime"":92,""critics_consensus"":""Toy Story 2 employs inventive storytelling, gorgeous animation, and a top notch voice cast to deliver another rich moviegoing experience for all ages, one that's arguably even better than its predecessor."",""release_dates"":{""theater"":""1999-11-24"",""dvd"":""2000-10-17""},""ratings"":{""critics_rating"":""Certified Fresh"",""critics_score"":100,""audience_rating"":""Upright"",""audience_score"":72},""synopsis"":"""",""posters"":{""thumbnail"":""http://content6.flixster.com/movie/10/93/63/10936392_mob.jpg"",""profile"":""http://content6.flixster.com/movie/10/93/63/10936392_pro.jpg"",""detailed"":""http://content6.flixster.com/movie/10/93/63/10936392_det.jpg"",""original"":""http://content6.flixster.com/movie/10/93/63/10936392_ori.jpg""},""abridged_cast"":[{""name"":""Tom Hanks"",""id"":""162655641"",""characters"":[""Woody""]},{""name"":""Tim Allen"",""id"":""162655909"",""characters"":[""Buzz Lightyear""]},{""name"":""Joan Cusack"",""id"":""162655020"",""characters"":[""Jessie the Cowgirl""]},{""name"":""Kelsey Grammer"",""id"":""162660300"",""characters"":[""Stinky Pete the Prospector""]},{""name"":""Don Rickles"",""id"":""341817905"",""characters"":[""Mr. Potato Head""]}],""alternate_ids"":{""imdb"":""0120363""},""links"":{""self"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9414.json"",""alternate"":""http://www.rottentomatoes.com/m/toy_story_2/"",""cast"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9414/cast.json"",""clips"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9414/clips.json"",""reviews"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9414/reviews.json"",""similar"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9414/similar.json""}},{""id"":""9559"",""title"":""Toy Story"",""year"":1995,""mpaa_rating"":""G"",""runtime"":80,""critics_consensus"":""As entertaining as it is innovative, Toy Story kicked off Pixar's unprecedented run of quality pictures, reinvigorating animated film in the process."",""release_dates"":{""theater"":""1995-11-22"",""dvd"":""2001-03-20""},""ratings"":{""critics_rating"":""Certified Fresh"",""critics_score"":100,""audience_rating"":""Upright"",""audience_score"":81},""synopsis"":"""",""posters"":{""thumbnail"":""http://content7.flixster.com/movie/10/93/63/10936393_mob.jpg"",""profile"":""http://content7.flixster.com/movie/10/93/63/10936393_pro.jpg"",""detailed"":""http://content7.flixster.com/movie/10/93/63/10936393_det.jpg"",""original"":""http://content7.flixster.com/movie/10/93/63/10936393_ori.jpg""},""abridged_cast"":[{""name"":""Tom Hanks"",""id"":""162655641"",""characters"":[""Woody""]},{""name"":""Tim Allen"",""id"":""162655909"",""characters"":[""Buzz Lightyear""]},{""name"":""Don Rickles"",""id"":""341817905"",""characters"":[""Mr. Potato Head""]},{""name"":""Jim Varney"",""id"":""162662792"",""characters"":[""Slinky Dog""]},{""name"":""Wallace Shawn"",""id"":""162671862"",""characters"":[""Rex""]}],""alternate_ids"":{""imdb"":""0114709""},""links"":{""self"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9559.json"",""alternate"":""http://www.rottentomatoes.com/m/toy_story/"",""cast"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9559/cast.json"",""clips"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9559/clips.json"",""reviews"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9559/reviews.json"",""similar"":""http://api.rottentomatoes.com/api/public/v1.0/movies/9559/similar.json""}}],""links"":{""self"":""http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=toy+story&page_limit=3&page=1"",""next"":""http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=toy+story&page_limit=3&page=2""},""link_template"":""http://api.rottentomatoes.com/api/public/v1.0/movies.json?q={search-term}&page_limit={results-per-page}&page={page-number}""}"
Dim obj As RootObject
obj = JsonConvert.DeserializeObject(Of RootObject)(json)
End Sub