Loop through returned JSON from an API - asp.net

I have the following JSON in asp.net VB:
Dim jsonString As String = "{'results':[ {'comments': 'some text', 'date' : 'some date', 'user':'aaa'},{'comments': 'some text2', 'date2' : 'some date2', 'user':'aaa2'}]} "
Dim json As JObject = JObject.Parse(jsonString)
How can I loop though the values like comments?
Thank you

The Newtonsoft documentation pages Querying JSON with LINQ and Querying JSON with SelectToken describe how you can query for values nested inside a JObject hierarchy once loaded.
For instance, using SelectTokens(), you can query for the comment values as follows:
' Get all comment values, convert them to simple strings, and store in an array:
Dim comments = json.SelectTokens("results[*].comments") _
.Select(Function(t) t.ToString()) _
.ToArray()
Here I am using the wildcard operator [*] to match all elements in the "results" array. This is a standard operator of JSONPath query syntax which SelectTokens() supports.
Here is the equivalent logic using LINQ:
Dim query = From item In json("results")
Let comment = item("comments")
Where comment IsNot Nothing
Select CType(comment, String)
Dim comments = query.ToArray()
Sample fiddle.

Related

Convert JSon to dynamic object in VB.Net

I am using VB.Net and calling salesforce API. It returns very ugly JSON which I am not able to deserialize. I have a following code using JSON.Net
Dim objDescription As Object = JsonConvert.DeserializeObject(Of Object)(result)
objDescription contains many properties, one on=f them in fields. But when I write something like objDescription.fields it gives me error.
objDescription.fields Public member 'fields' on type 'JObject' not found. Object
I am not very sure but I think it C# allow to convert any JSON to dynamic object. How can I use it in VB.Net?
You can turn Option Strict Off and use ExpandoObject which is recognized by JSON.NET. In order to leverage the dynamic features you can use a variable of type object.
Option Strict Off
Sub Main
Dim jsonData As Object = JsonConvert.DeserializeObject(Of System.Dynamic.ExpandoObject)("{""Id"":25}")
Dim test As Integer = jsonData.Id
Console.WriteLine(test)
End Sub
If you would like to use JObject because you need some of its features, you can index the JObject instead.
Sub Main
Dim jsonData As Object = JsonConvert.DeserializeObject(Of Object)("{""Id"":25}")
Dim test = jsonData("Id")
Console.WriteLine(test)
End Sub

Visual basic and Json.net Web request

Basically what im trying to do is make a program that list game information for league of legends.. using there API to extract data. how this works is you Search there username and it returns an integer linked to that account, you then use that integer to search for all of the information for that account, EG account level, wins, losses, etc.
I've run into a problem i can't seem to figure out.. Please not that I'm very new to Json.net so have little experience about working with it.. Below is how the search for the user ID is found, The First section is the Username Minus Any spaces in the name the next is the ID which is the information i require.
{"chucknoland":{"id":273746,"name":"Chuck Noland","profileIconId":662,"summonerLevel":30,"revisionDate":1434821021000}}
I must be declaring the variables wrong in order to obtain the data as everything i do it returns as 0.
these are the following class i have to store the ID within
Public Class ID
Public Shared id As Integer
Public Shared name As String
End Class
Looking at a previous example seen here Simple working Example of json.net in VB.net
They where able to resolve there issue by making a container class with everything inside it.. My problem is that The data i seek i always changing.. The first set will always be different to the "Chucknoland" that's displayed in the example.. is someone able to explain how i could go about extracting this information?
Please note that the variables rRegion has the value of what server there on, Chuck Noland is on OCE, and sSearch is the Username.. Due to Problems with API keys i had to remove the API key from the code... But the URL returns the Json Provided.
'URL string used to grab Summoner ID
jUrlData = "https://oce.api.pvp.net/api/lol/" + rRegion + "/v1.4/summoner/by-name/" + sSearch +
' Create a request for URL Data.
Dim jsonRequest As WebRequest = WebRequest.Create(jUrlData)
'request a response from the webpage
Dim jsonResponse As HttpWebResponse = CType(jsonRequest.GetResponse(), HttpWebResponse)
'Get Data from requested URL
Dim jsonStream As Stream = jsonResponse.GetResponseStream()
'Read Steam for easy access
Dim jsonReader As New StreamReader(jsonStream)
'Read Content
Dim jsonResponseURL As String = jsonReader.ReadToEnd()
jUrlString = jsonResponseURL
this is the request i have to obtain the information, and this is the code i tried to use to display the ID for that json.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim obj As ID
obj = JsonConvert.DeserializeObject(Of ID)(jUrlString)
MsgBox(obj.id)
End Sub
Is anyone able to explain how i can go about getting this to work?
One way to handle this would be to get the item into a Dictionary where the keys are the property names.
The class you have is not quite right unless you only want name and id and not the rest of the information. But using a Dictionary you wont need it anyway. The "trick" is to skip over the first part since you do not know the name. I can think of 2 ways to do this, but there are probably more/better ways.
Since json uses string keys pretty heavily, create a Dictionary, then get the data from it for the actual item:
jstr = ... from whereever
' create a dictionary
Dim jResp = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jstr)
' get the first/only value item
Dim jobj = jResp.Values(0) ' only 1 item
' if you end up needing the name/key:
'Dim key As String = jResp.Keys(0)
' deserialize first item to dictionary
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jobj.ToString)
' view results
For Each kvp As KeyValuePair(Of String, Object) In myItem
Console.WriteLine("k: {0} v: {1}", kvp.Key, kvp.Value.ToString)
Next
Output:
k: id v: 273746
k: name v: Chuck Noland
k: profileIconId v: 662
k: summonerLevel v: 30
k: revisionDate v: 1434821021000
Using String, String may also work, but it would convert numerics to string (30 becomes "30") which is usually undesirable.
While poking around I found another way to get at the object data, but I am not sure if it is a good idea or not:
' parse to JObject
Dim js As JObject = JObject.Parse(jstr)
' 1 = first item; 2+ will be individual props
Dim jT As JToken = js.Descendants(1)
' parse the token to String/Object pairs
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jT.ToString)
Same results.

How does one set a property of a JsonObject dynamically?

I am using a method of passing Json to and from my markup using jquery and ajax. This can be described in more detail on this page: http://blogs.telerik.com/aspnet-ajax/posts/12-04-27/the-present-and-future-of-using-json-in-webforms.aspx
In this snippet of code, I try to set the object's value dynamically by setting a string variable named "test" to a business object's value:
Dim objOrder As Object = New JsonObject()
For Each Order As BoVendorOrder In Orders
Dim Vendor As New BoVendor(Order.VendorID)
Dim test As String = Order.VendorOrderID
objOrder.test = Vendor.VendorName + " - " + Order.VendorOrderPoNumber
Next
I left out some code for the sake of brevity. The goal is to get the objOrder.test to be equal to the VendorOrderID (a number in our SQL database) so that the JSON looks like this:
{
"123456": "VendorName - PONumber",
"678901": "VendorName - PONumber"
}
Any of you guys out there know how to do this?
Do you really need the order IDs to be properties of the object? It might be easier to just return a serialized Dictionary(Of String, String). You could still look up by order ID and it would be easier to loop over than the props of the Javascript object.
Here's an example of what you'd need to do using the dictionary approach:
Dim OrdersDict as New Dictionary(Of String, String)()
For Each Order as BoVendorOrder In Orders
If Not OrdersDict.ContainsKey(Order.VendorOrderID) Then
OrdersDict.Add(Order.VendorOrderID, Vendor.VendorName + " - " + Order.VendorOrderPoNumber)
End If
Next
' Serialize the dictionary object to JSON
' Using System.Web.Script.Serialization.JavascriptSerializer:
Dim Serializer As New JavaScriptSerializer
If MaxLength Then Serializer.MaxJsonLength = Int32.MaxValue
Dim x as String = Serializer.Serialize(OrdersDict) 'Return or response.write x as needed
'or
'Using JSON.net
Dim x as String = JsonConvert.SerializeObject(OrdersDict) 'Return or response.write x as needed

How to insert a " into sqlite3 text

I want to insert a string ,like Hello ,I am "Tmacy"!,into a sqlite3 table.But I can't find a way to insert the ".(ps.I tried to use \" instead of ", but it doesn't word.). Note:I use the C/C++ API function sqlite3_exec to insert the string into sqlite table.If you insert it with the sqlite3 command , it may works .
like that:
sprintf(sqlcmd,"insert into dict values('%s','%s')",word,meaning);
if(sqlite3_exec(data,sqlcmd,NULL,NULL,&errmsg) != SQLITE_OK){
printf("insert error!:%s\n",errmsg);
}else{
printf("insert success!\n");
}
Thanks!
The sqlite3_mprintf function has formats like %Q that allow you to format strings correctly:
char *sql = sqlite3_mprintf("INSERT INTO dict VALUES(%Q,%Q)", word, meaning);
err = sqlite3_exec(data, sql, NULL, NULL, &errmsg);
sqlite3_free(sql);
Try repeating the quote instead of escaping it :-
http://www.sqlite.org/faq.html#q14
You'd be better off using parameters here, it's safer then simply making slight changes to the text strings so that " and such don't cause a crash. Some sample code of using parameters in one of my own projects, in VB .net.
Public Sub RunSQLiteCommand(ByVal CommandText As String, Optional ByVal ReadDataCommand As Boolean = False, Optional ByVal ParameterList As Hashtable = Nothing)
SQLcommand.Parameters.Clear()
SQLcommand.CommandText = CommandText
If ParameterList IsNot Nothing Then
For Each key As String In ParameterList.Keys
SQLcommand.Parameters.Add(New SQLite.SQLiteParameter(key, ParameterList(key)))
Next
End If
SQLcommand.ExecuteNonQuery()
If ReadDataCommand Then
SQLreader = SQLcommand.ExecuteReader()
End If
End Sub
If you really want to avoid using parameters though, then "" (two of them) would be the way to go. If I'm ever not using parameters I run all string values I'm inserting into the database through a function that replaces " with "" everywhere in the string value.
Edit: Oh yeah, I almost forgot. For using parameters, your key value should be '#FieldName', and your SQL Query should say '#FieldName' wherever you use that parameter.
So for example if you call your field 'Name' that you want to insert the " in, you'd have something like this for insert query.
insert into dict values(#Name, #OtherField)
You could call your parameter anything you want, it's just easier if you name it the same thing as the field you're loading the value into.

Getting values from any URL

I have this url : http://localhost:49500/Learning/Chapitre.aspx?id=2
How can I get just the value of id in this url ?
You can access all the query strings through the Request.QueryString() array:
Request.QueryString("id") will give you the 2
Despite my own comment saying it has been answered, here is the code.
Dim idval As String = System.Web.HttpUtility.ParseQueryString("http://localhost:49500/Learning/Chapitre.aspx?id=2")("id")
Create a new instance of System.Uri class with the URL and the use the Query property to get the query string part.
Once you have that string, do String.Split on the '&' character. For each string in the resulting array, do String.Split on the '=' char. In the resulting array, the first string is the query parameter name, the second is the value (if present). Check if the name is the one you are interested in and if it is, get the value.
Update: Boy, I haven't touched VB since 1999... :-)
Here's the code for my answer. I didn't realize that the Url you want to parse is the page Url. For that specific case, Request.QueryString("id") will indeed be a better solution.
Dim url As Uri = New Uri("http://localhost:49500/Learning/Chapitre.aspx?id=2")
Dim query As String = url.Query.Trim("?")
Dim parameters() As String = query.Split("&")
Dim tokens() As String
Dim value As String = ""
For index As Integer = 0 To parameters.Length - 1
tokens = parameters(index).Split("=")
If tokens(0).ToLower = "id" Then
If tokens.Length = 2 Then
value = tokens(1)
End If
Exit For
End If
Next
' At this point value contains the parameter value or
' is empty if the parameter has no value or if the parameter is not present
You can use Request vb method
Using the url : http://localhost:49500/Learning/Chapitre.aspx?id=2
Dim valueId = Request("id")
to test the code:
response.Write(valueId)
value Id is 2

Resources