JSON - jResults/VB error - json

I am trying to take the value of a result JSON using VB(JSON.NET).
JSON
"paging": - {
"offset": 0,
"limit": 200,
"total": 6,
},
"results": - [
- {
"user_id": 010101,
"name": "Name X",
"nickname": "XXXX",
"points": 0
},
- {
"user_id": 0222101,
"name": "Name X2",
"nickname": "YYYY",
"points": 0
}
My code:
request = DirectCast(WebRequest.Create(campos.url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp, teste As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
'Dim results As List(Of JToken) = jResults.Children().ToList()
teste = jResults("results")("nickname").ToString()
I need to take the nickname, however do not achieve. In the truth, achieve only take values of the ítem PAGING and any of RESULTS.
But is giving error, he does not achieve to find the values.
Help me?
tks!

Related

Deserialized an object into a DataTable

I have a JSON response like this:
{ "cod": "OK",
"list": [
{ "date": "31\/10\/2018", "count": "109", "name": "PAUL" },
{ "date": "30\/09\/2018", "count": "103", "name": "LUKE" }
]}
I use:
Dim jss As New JavaScriptSerializer
Dim Response = jss.Deserialize(Of Object)(strResponse)
Dim Cod = Response("cod")
Then:
Dim Lista_documents = Response("list")
And I have an object with the list of documents.
How can I populate a new DataTable?
I am not aware of any methods that will do it automatically, so probably with a Loop.
Dim table As New DataTable
table.Columns.Add("date", GetType(Date))
table.Columns.Add("count", GetType(Integer))
table.Columns.Add("name", GetType(String))
For Each Li In Lista_documents
table.Rows.Add(Li("date"), Li("count"), Li("name"))
Next
Adjust depending on how your Lista_documents is structured

vb.net get values from json like string in DataTable

Here is my json like string:
{
"ProductGroupId": "3",
"ProductGroupName": "Frisdranken",
"ProductId": "139",
"ProductName": "Cola",
"Quantity": 1,
"QuantityUnit": "P",
"SellingPrice": 2.7,
"VatRateId": "A",
"DiscountLines": []
}, {
"ProductGroupId": "3",
"ProductGroupName": "Frisdranken",
"ProductId": "146",
"ProductName": "Plat water",
"Quantity": 1,
"QuantityUnit": "P",
"SellingPrice": 2.6,
"VatRateId": "A",
"DiscountLines": []
}
How do I get the "ProductName" and "Quantity" in a datatable?
Assuming your json is an array and you just missed the enclosing [...], you can:
Dim json As String = "[{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""139"",""ProductName"":""Cola"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.7,""VatRateId"":""A"",""DiscountLines"":[]},{""ProductGroupId"":""3"",""ProductGroupName"":""Frisdranken"",""ProductId"":""146"",""ProductName"":""Plat water"",""Quantity"":1,""QuantityUnit"":""P"",""SellingPrice"":2.6,""VatRateId"":""A"",""DiscountLines"":[]}]"
'Use JSON.Net to obtain a JArray
Dim jobj As JArray = JsonConvert.DeserializeObject(json)
'Extract just the fields you want from the data with a Linq projection into
'anonymous type with ProductName and Quantity fields
Dim ProductsAndQuantities = jobj.Select(Function(j)
Return New With {
.ProductName = j("ProductName"),
.Quantity = j("Quantity")}
End Function)
'build your DataTable
Dim dt As DataTable = New DataTable()
dt.Columns.Add("ProductName")
dt.Columns.Add("Quantity")
'Load the data table
For Each item In ProductsAndQuantities
Dim dr As DataRow = dt.NewRow()
dr("ProductName") = item.ProductName
dr("Quantity") = item.Quantity
dt.Rows.Add(dr)
Next

Getting values from twitch.tv JSON response

I have just started using JSON.NET and I am having some trouble getting the values from JSON items.
I have come across some code over the past few days which will allow me to grab the names but not he associated values.
I am working with the twitch.tv Web API. Here is my code:
Dim sUrl As String = Convert.ToString("https://api.twitch.tv/kraken/streams/") & sUsername
Dim wRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(sUrl), HttpWebRequest)
wRequest.ContentType = "application/json"
wRequest.Accept = "application/vnd.twitchtv.v3+json"
wRequest.Method = "GET"
Dim wResponse As WebResponse = wRequest.GetResponse()
Dim dataStream As Stream = wResponse.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim res As String = reader.ReadToEnd()
Dim outer As JToken = JToken.Parse(res)
Dim inner As JObject = outer("stream").Value(Of JObject)()
Dim keys As List(Of String) = inner.Properties().[Select](Function(p) p.Name).ToList()
For Each k As String In keys
Debug.WriteLine(k)
Next
reader.Close()
wResponse.Close()
The raw JSON is as follows:
{
"_links": {
"self": "https: //api.twitch.tv/kraken/streams/jojosaysbreee",
"channel": "https: //api.twitch.tv/kraken/channels/jojosaysbreee"
},
"stream": {
"_id": 16717827552,
"game": "TomClancy'sRainbowSix: Siege",
"viewers": 15,
"created_at": "2015-09-30T21: 19: 10Z",
"video_height": 720,
"average_fps": 59.9630366205,
"is_playlist": false,
"_links": {
"self": "https: //api.twitch.tv/kraken/streams/jojosaysbreee"
},
"preview": {
"small": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-80x45.jpg",
"medium": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-320x180.jpg",
"large": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-640x360.jpg",
"template": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-{width}x{height}jpg"
},
"channel": {
"_links": {
"self": "http: //api.twitch.tv/kraken/channels/jojosaysbreee",
"follows": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/follows",
"commercial": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/commercial",
"stream_key": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/stream_key",
"chat": "http: //api.twitch.tv/kraken/chat/jojosaysbreee",
"features": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/features",
"subscriptions": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/subscriptions",
"editors": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/editors",
"videos": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/videos",
"teams": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/teams"
},
"background": null,
"banner": null,
"broadcaster_language": "en",
"display_name": "JOJOsaysbreee",
"game": "TomClancy'sRainbowSix: Siege",
"logo": "http: //static-cdn.jtvnw.net/jtv_user_pictures/jojosaysbreee-profile_image-26a326e1c867f257-300x300.jpeg",
"mature": true,
"status": "BetaHype<3",
"partner": false,
"url": "http: //www.twitch.tv/jojosaysbreee",
"video_banner": "http: //static-cdn.jtvnw.net/jtv_user_pictures/jojosaysbreee-channel_offline_image-67b08d519585b45f-640x360.jpeg",
"_id": 41382559,
"name": "jojosaysbreee",
"created_at": "2013-03-16T09: 33: 34Z",
"updated_at": "2015-10-01T05: 15: 26Z",
"delay": null,
"followers": 2318,
"profile_banner": "http: //static-cdn.jtvnw.net/jtv_user_pictures/jojosaysbreee-profile_banner-6abce6a882f4f9e4-480.jpeg",
"profile_banner_background_color": "#ffffff",
"views": 15939,
"language": "en"
}
}
}
The response from the code is all the names from "stream":
_id
game
viewers
created_at
video_height
average_fps
is_playlist
_links
preview
channel
What I am trying to accomplish is getting all the associated values after each one of those items but I cannot seem to get it right. I know it needs to iterate deeper but I've tried IEnumerable method and was unsuccessful there also.
Any and all help is much appreciated.
You're selecting all of the property names into a list with this line:
Dim keys As List(Of String) = inner.Properties().[Select](Function(p) p.Name).ToList()
You won't be able to get anything other than the property names from keys this way. Instead, loop over the Properties() collection and examine each JProperty:
For Each prop As JProperty In inner.Properties()
Debug.WriteLine("{0} - {1}", prop.Name, prop.Value)
Next
In addition, I'd recommend a few changes. The code you're using to make the request is harder than it should be :)
Dim sUrl As String = Convert.ToString("https://api.twitch.tv/kraken/streams/") & sUsername
No need to call Convert.ToString("") - it's already a string. And (although it's a matter of opinion), I think Hungarian notation for the variables isn't necessary. This is much simpler:
Dim url As String = "https://api.twitch.tv/kraken/streams/" & username
Much easier to just use WebClient:
Dim client As New WebClient()
client.Headers.Add(HttpRequestHeader.Accept, "application/vnd.twitchtv.v3+json")
Dim responseJson = client.DownloadString(url)
Complete example:
Dim username As String = "???"
Dim url As String = "https://api.twitch.tv/kraken/streams/" & username
Dim client As New WebClient()
client.Headers.Add(HttpRequestHeader.Accept, "application/vnd.twitchtv.v3+json")
Dim responseJson As String = client.DownloadString(url)
Dim outer As JToken = JToken.Parse(responseJson)
Dim inner As JObject = outer("stream").Value(Of JObject)
For Each prop As JProperty In inner.Properties()
Console.WriteLine($"{prop.Name} - {prop.Value}")
Next
Easy peasy! :)

VB.NET need help in deserialization of a JSON

Hey I need help in deserializing this:
{
"success": true,
"rgInventory": {
"2722309060": {
"id": "2722309060",
"classid": "939801430",
"instanceid": "188530139",
"amount": "1",
"pos": 1
},
"2722173409": {
"id": "2722173409",
"classid": "937254203",
"instanceid": "188530139",
"amount": "1",
"pos": 2
},
"2721759518": {
"id": "2721759518",
"classid": "720293857",
"instanceid": "188530139",
"amount": "1",
"pos": 3
},
"2721748390": {
"id": "2721748390",
"classid": "310777652",
"instanceid": "480085569",
"amount": "1",
"pos": 4
}
}
}
at the end it should look like:
2722309060#2722173409#2721759518#2721748390
Dim result = JsonConvert.DeserializeObject(jsonstring) 'deserialize it
Dim tempfo As String = result("rgInventory").ToString 'get rgInventory
Console.WriteLine(tempfo)
how i can deserialize all 'id's?
The json contains a Dictionary of items, the IDs you want are the keys. If you deserialized it, you could get them from the Dictionary. Otherwise, you can use JParse and linq to get them:
Dim jstr As String = ...
' parse the json
Dim js As JObject = JObject.Parse(jstr)
' extract the inventory items
Dim ji As JObject = JObject.Parse(js("rgInventory").ToString)
' get and store the keys
Dim theIds As List(Of String) = ji.Properties.Select(Function(k) k.Name).ToList()
I suspect that when "success" is false that the resulting items list will be empty. Test that it works:
For Each s As String In theIds
Console.WriteLine(s)
Next
Result:
2722309060
2722173409
2721759518
2721748390

I need help getting json data to my vb.net

I have the following code, using Newtonsoft.Json:
Dim address2 As String =
"https://euw.api.pvp.net/api/lol/euw/v2.5/league/by-summoner/"
& FlatLabel7.Text & "/entry?api_key=API KEY"
Dim client2 As WebClient = New WebClient()
Dim reader2 As StreamReader = New StreamReader(client2.OpenRead(address2))
Dim json2 As JObject = JObject.Parse(reader2.ReadToEnd)
FlatTextBox2.Text = json2.SelectToken(FlatLabel7.Text).SelectToken("tier")
but it doesnt find the "tier".
The json goes like this:
{"28170580": [{
"queue": "RANKED_SOLO_5x5",
"name": "Name"
"entries": [{
"leaguePoints": 54,
"isFreshBlood": false,
"isHotStreak": false,
"division": "I",
"isInactive": false,
"isVeteran": false,
"losses": 32,
"playerOrTeamName": "asdfasda",
"playerOrTeamId": "ffdsfsaf",
"wins": 34
}],
"tier": "SILVER"
}]}
I think its because it must go to a [0] before entering the "tier", but i dont know how to do it.
Thanks in advance.