Simple working Example of json.net in VB.net - json

I have the following simplified JSON string from a provider, its been a long time since I used Visual Studio and vb.Net, so I'm very rusty!
{
"Venue": {
"ID": 3145,
"Name": "Big Venue, Clapton",
"NameWithTown": "Big Venue, Clapton, London",
"NameWithDestination": "Big Venue, Clapton, London",
"ListingType": "A",
"Address": {
"Address1": "Clapton Raod",
"Address2": "",
"Town": "Clapton",
"County": "Greater London",
"Postcode": "PO1 1ST",
"Country": "United Kingdom",
"Region": "Europe"
},
"ResponseStatus": {
"ErrorCode": "200",
"Message": "OK"
}
}
}
I want to use JSON.Net to turn this in to something I can work with, I have read examples etc and JSON.net looks like the answer, but I'm getting no where.
My .Net code (Me.TextBox1.Text contains the JSON shown above)
Imports Newtonsoft.Json
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj As JSON_result
obj = JsonConvert.DeserializeObject(Of JSON_result)(Me.TextBox1.Text)
MsgBox(obj.ID)
End Sub
End Class
Public Class JSON_result
Public ID As Integer
Public Name As String
Public NameWithTown As String
Public NameWithDestination As String
Public ListingType As String
End Class
Can someone explain why obj.ID always ends up as 0 please, and why none of the other properties of my class are populated and what I need to do to fix this, no errors are reported.

Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue".
So either create a class for that, e.g.:
Public Class Container
Public Venue As JSON_result
End Class
Public Class JSON_result
Public ID As Integer
Public Name As String
Public NameWithTown As String
Public NameWithDestination As String
Public ListingType As String
End Class
Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)
or change your JSON string to
{
"ID": 3145,
"Name": "Big Venue, Clapton",
"NameWithTown": "Big Venue, Clapton, London",
"NameWithDestination": "Big Venue, Clapton, London",
"ListingType": "A",
"Address": {
"Address1": "Clapton Raod",
"Address2": "",
"Town": "Clapton",
"County": "Greater London",
"Postcode": "PO1 1ST",
"Country": "United Kingdom",
"Region": "Europe"
},
"ResponseStatus": {
"ErrorCode": "200",
"Message": "OK"
}
}
or use e.g. a ContractResolver to parse the JSON string.

Imports Newtonsoft.Json.Linq
Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

In Place of using this
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
You can also use
MsgBox(json.SelectToken("Venue.ID"))

Related

VB.net VB Serializing JSON Property Name issue

I'm having an issue with a JSON property name. It might be because I don't know what I'm doing. This is my 1st attempt at serializing JSON (with vb.net VB)
The result I'm looking for is this:
{
"login": {
"username": "XXX",
"password": "pwxXXxx",
"busId": "123456789",
"busRole": "Third Party",
"paymentTerms": "Prepaid"
}
}
This is what I am getting:
[
{
"login": null,
"username": "1234",
"password": "pw123456",
"busId": "12345",
"busRole": "Third Party",
"paymentTerms": "Prepaid"
}
]
My issue is with the piece "login": {" adds the colon and the term null. I'll post my code below
Any help would be appreciated.
-Thank You
Partial Class _Default
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim loads As New List(Of fgtload)()
loads.Add(New fgtload() With {
.username = "1234",
.password = "pw123456",
.busId = "12345",
.busRole = "Third Party",
.paymentTerms = "Prepaid"
}
)
Dim strserialize As String = JsonConvert.SerializeObject(loads)
lblserial.Text = strserialize
End Sub
Public Class fgtload
<JsonProperty(PropertyName:="login")>
Public Property login As String
Public Property username() As String
Get
Return m_username
End Get
Set
m_username = Value
End Set
End Property
Private m_username As String
Public Property password() As String
Get
Return m_password
End Get
Set
m_password = Value
End Set
End Property
Private m_password As String
Public Property busId() As String
Get
Return m_busId
End Get
Set
m_busId = Value
End Set
End Property
Private m_busId As String
Public Property busRole() As String
Get
Return m_busRole
End Get
Set
m_busRole = Value
End Set
End Property
Private m_busRole As String
Public Property paymentTerms() As String
Get
Return m_paymentTerms
End Get
Set
m_paymentTerms = Value
End Set
End Property
Private m_paymentTerms As String
End Class
Here's the entire JSON output sampel Im trying to get.
{
"login": {
"username": "XXX",
"password": "pwxXXxx",
"busId": "123456789",
"busRole": "Third Party",
"paymentTerms": "Prepaid"
}
}
,
"details": {
"serviceClass": "STD",
"typeQuery": "QUOTE",
"pickupDate": "20200221",
"productCode": "DFQ"
},
"originLocation": {
"city": "Keyport",
"state": "NJ",
"postalCode": "07735",
"country": "USA",
"locationType": "COMM"
},
"destinationLocation": {
"city": "Beverly Hills",
"state": "CA",
"postalCode": "90210",
"country": "USA",
"locationType": "COMM"
},
"listOfCommodities": {
"commodity": [
{
"packageLength": 48,
"packageWidth": 48,
"packageHeight": 48,
"weight": 1500,
"handlingUnits": 1,
"packageCode": "PLT"
}
]
}
}
How would I add another class to the wrapper. For example
Public Class fgtDetails '
Public ServiceClass As String
Public typeQuery As String
Public pickupDate As Integer
Public productCode As String
End Class
From what I can see, you are trying to declare the login element as an empty string and is therefore serialized as null. From what you said you are trying to achieve, you want to declare login as an object that contains the Username, Password, BusID, BusRole, and PaymentTerms properties.
From what your looking for, the Login property is an object, but you are declaring it as a string. Also, you are creating a list and serializing that, which is leading to those square brackets ([, ]) around your JSON. Square brackets mark arrays or enumerations, whereas in your sample JSON you are just looking for an object.
One last tip, for classes that are used for serializing, you don't have to use properties. You can just declare your variables as public variables. The only time you need to use properties is if you need to modify or do something with its contents when it's being set or read. e.g., formatting a string when it's being set, or calculating a response when the variable is being retrieved (you can put code in the GET and SET methods to make them act like a function).
Something to note with serializing and deserializing, you can nest classes. When serialized they will be converted to JSON objects using the same object layout and variable name. So you can try something like this:
(UPDATED CODE)
Public Sub CreateJson()
'Create Wrapper Object
Dim Load As New fgtload
Load.Login = New fgtLoginData With { 'Create Login Data
.Username = "XXX",
.Password = "pwxXXxx",
.BusID = 123456789,
.BusRole = "Third Party",
.PaymentTerms = "Prepaid"
}
Load.Details = New fgtDetailsData With { 'Create Details
.ServiceClass = "STD",
.TypeQuery = "QUOTE",
.PickupDate = "20200221",
.ProductCode = "DFQ"
}
Load.OriginLocation = New fgtLocationnData With { 'Create Origin
.City = "Keyport",
.State = "NJ",
.PostalCode = 7735,
.Country = "USA",
.LocationType = "COMM"
}
Load.DestinationLocation = New fgtLocationnData With { 'Create Destination
.City = "Beverly Hills",
.State = "CA",
.PostalCode = 90210,
.Country = "USA",
.LocationType = "COMM"
}
'Create Commodities
Dim Commodity1 As New fgtCommodity With {
.PackageLength = 48,
.PackageWidth = 48,
.PackageHeight = 48,
.Weight = 1500,
.HandlingUnits = 1,
.PackageCode = "PLT"
}
'Add commodity to load
Load.ListOfCommodities.commodity.Add(Commodity1)
'Serialize wrapper object
Dim Json As String = JsonConvert.SerializeObject(Load)
End Sub
Public Class fgtload 'Primary wrapper
Public Login As New fgtLoginData
Public Details As New fgtDetailsData
Public OriginLocation As New fgtLocationnData
Public DestinationLocation As New fgtLocationnData
Public ListOfCommodities As New fgtCommodityWrapper
End Class
Public Class fgtLoginData 'Login Data
Public Username As String
Public Password As String
Public BusID As String
Public BusRole As String
Public PaymentTerms As String
End Class
Public Class fgtDetailsData 'Details Data
Public ServiceClass As String
Public TypeQuery As String
Public PickupDate As String
Public ProductCode As String
End Class
Public Class fgtLocationnData 'Location data for both Origin and Destination
Public City As String
Public State As String
Public PostalCode As String
Public Country As String
Public LocationType As String
End Class
Public Class fgtCommodityWrapper 'Commodity Data
Public commodity As New List(Of fgtCommodity) ' Lists get serialized into arrays
End Class
Public Class fgtCommodity
Public PackageLength As Double 'Doubles to allow floating-point numbers
Public PackageWidth As Double
Public PackageHeight As Double
Public Weight As Double
Public HandlingUnits As Integer
Public PackageCode As String
End Class
This creates this response.
(UPDATED OUTPUT)
{
"Login": {
"Username": "XXX",
"Password": "pwxXXxx",
"BusID": "123456789",
"BusRole": "Third Party",
"PaymentTerms": "Prepaid"
},
"Details": {
"ServiceClass": "STD",
"TypeQuery": "QUOTE",
"PickupDate": "20200221",
"ProductCode": "DFQ"
},
"OriginLocation": {
"City": "Keyport",
"State": "NJ",
"PostalCode": "7735",
"Country": "USA",
"LocationType": "COMM"
},
"DestinationLocation": {
"City": "Beverly Hills",
"State": "CA",
"PostalCode": "90210",
"Country": "USA",
"LocationType": "COMM"
},
"ListOfCommodities": {
"commodity": [
{
"PackageLength": 48.0,
"PackageWidth": 48.0,
"PackageHeight": 48.0,
"Weight": 1500.0,
"HandlingUnits": 1,
"PackageCode": "PLT"
}
]
}
}
Hope this helps.
(UPDATE NOTES):
In response to your comment, I have modified the code in my response to allow or your updated expected output.
Note also that if two JSON objects have the same structure (in this case originLocation and destinationLocation) you can use the same class.
Also, see at the Commodity Data there are square brackets, this marks a JSON array. Arrays/Lists/Enumerations in your code will be serialized into JSON arrays, even if they are of a class type. So in this code example, you can add as many commodities to ListOfCommodities.commodity as you want and they will be properly serialized into JSON.

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

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).

Need help deserializing json data

i have the following json string
{
"Count": 10,
"Page": 0,
"Queue": [
{
"id": "146648",
"number": "96599004970"
},
{
"id": "146647",
"number": "96599004970"
},
{
"id": "146646",
"number": "96599004970"
},
{
"id": "146645",
"number": "96599004970"
},
{
"id": "146644",
"number": "96599004970"
},
{
"id": "146643",
"number": "96599004970"
},
{
"id": "146642",
"number": "96599004970"
},
{
"id": "146641",
"number": "96599004970"
},
{
"id": "146640",
"number": "96599004970"
},
{
"id": "146639",
"number": "96599004970"
}
]
}
i'm using vb.net with newtonstoft json
i made these classes
Public Class Queue
Public Property Count As Integer
Public Property Page As Integer
Public Property Msgs As List(Of Msg)
End Class
Public Class Msg
Public Property id As String
Public Property number As String
End Class
I used this code to deserialize this string
Dim getQueue as Queue
getQueue = JsonConvert.DeserializeObject(Of Queue)(jsonString)
how can i rebuild the array? or retreive data from that queue object
any help is appreciated
To make your json string deserialized properly, your mapping class should look like this instead :
Public Class RootObject
Public Property Count As Integer
Public Property Page As Integer
Public Property Queue As List(Of Queue)
End Class
Public Class Queue
Public Property id As String
Public Property number As String
End Class
Then you can do as follow :
Dim getQueue as RootObject
getQueue = JsonConvert.DeserializeObject(Of RootObject)(jsonString)
For Each Q As Queue In getQueue.Queue
'here you can access each Queue object
Next
NB: above class definitions are translated from C# classes generated using http://json2csharp.com/ tool. That is a handy online tool to generate classes suitable for mapping your json.
The following code prints id and number values for each msgs:
For Each msg As Msg In getQueue.Msgs
Console.WriteLine("id: " + msg.id & ", number: " + msg.number)
Next
try this. Sorry its in C# as I dont know VB.net
var JsonStr = JsonConvert.DeserializeObject<Queue>(jsonString);
label1.Text = JsonStr.Count
label2.Text = JsonStr.Page
for (int i = 0; i < JsonStr.Msg.Count; i++)
{
label3.Text = JsonStr.Msg[i].id;
label4.Text = JsonStr.Msg[i].number;
}

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