I need result from this JSON:
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjBGOTkyNkZFQTUyOTgxRjZDMjBENUMzNUQ0NjUxMzAzQ0QzQzBFMzIiLCJ0eXAiOiJhdCtqd 3QiLCJ4NXQiOiJENWttX3FVcGdmYkNEVncxMUdVVEE4MDhEakkifQ.eyJuYmYiOjE2MjA3NzEyNDEsImV4cCI6MTYyMDc3NDg0MSwiaXNzIjoiaH R0cHM6Ly9pZC5wcmVwcm9kLmV0YS5nb3YuZWciLCJhdWQiOiJJbnZvaWNpbmdBUEkiLCJjbGllbnRfaWQiOiJlZWQ4YWY2MS01ZjRmLTQxM2MtYWZlN S1jYjg0YjBiOTlhOGMiLCJJbnRlcm1lZElkIjoiMCIsIkludGVybWVkUklOIjoiIiwiSW50ZXJtZWRFbmZvcmNlZCI6IjIiLCJuYW1lIjoiMjAyNDY5NzM 1OmVlZDhhZjYxLTVmNGYtNDEzYy1hZmU1LWNiODRiMGI5OWE4YyIsInNpZCI6IjJiYzcxYTlhLWQ1MzAtMzc1ZC0zNjMzLTUwN2E3OWFjY2Y1ZiIsInByZW ZlcnJlZF91c2VybmFtZSI6IkVSUCIsIlRheElkIjoiNTE4MDEiLCJUYXhSaW4iOiIyMDI0Njk3MzUiLCJQcm9mSWQiOiI1NDgxNCIsIklzVGF4QWRtaW4iO
iIwIiwiSXNTeXN0ZW0iOiIxIiwiTmF0SWQiOiIiLCJzY29wZSI6WyJJbnZvaWNpbmdBUEkiXX0.IIxTKWdH0cUInlzrIMON95f7S6vW-CBfRoK8ZxOI6mqp
DbRLBaZQZyNoYl4A6JYQR6FJY4YVIFUsAbkKEKwwB1MaOpMMWmkyySfUmgvBMvEo6EZnT-oewnSd2EPF_bIK7-HTGug7Rjdy__wTpBr-6PH5kzR79xXzNh_s
R7TIPcvjJ-nx7eNZREdk4J7M3X8Mfjzww2RkbizN5zXNpmc5OHh_VLtlkA-4zQrs102HA9VFTxLEIdXhrpBqEBmy9dt-onZpuiKbkioV5iH2uwAkQbDvnM9h
p7EJscL0y0xFjfwbAUxQx3ohcXtA31fwyYazKQVKHCtNm9SPgSsQ-rKevQ",
"expires_in": 3600,
"scope": "Accecc DB"
}
I used:
Dim Mytoken As JObject = JObject.Parse(TextBox1.Text)
TextBox2.Text = Mytoken.SelectToken("access_token").ToString
Now I Need to get the uuid, longId, internalId, and hashKey from the acceptedDocuments like this:
{
"submissionId": "5hfhfgy5653uytyu45fg457",
"acceptedDocuments": [
{
"uuid": "hlg5fdg7ggnjgh",
"longId": "jgjhk78jm,jhk54567ujnfgh7fggh",
"internalId": "477",
"hashKey": "dfgdfhdyjfghryjghjj"
}
],
"rejectedDocuments": []
}
You could use Newtonsoft.Json and deserialize the response into an object:
Imports Newtonsoft.Json
Public Class Submission
Public submissionId As String
Public acceptedDocuments As List(Of AcceptedDocuments)
Public rejectedDocuements As String 'not sure of the type of this property
End Class
Public Class AcceptedDocuments
Public uuid As String
Public longId As String
Public internalId As Integer
Public hashKey As String
End Class
Public Function DeserilizeJson(ByRef json As String) As Submission
Dim doc As Submission = JsonConvert.DeserializeObject(Of Submission)(json)
Return doc
End Function
This should result in a Submission class object being created, to which you can reference all of the members of it, including the List of AcceptedDocuments (you can iterate over the list as needed).
I solved the problem
Dim Mytoken As JObject = JObject.Parse(TextBox1.Text)
TextBox2.Text = "My submissionId IS: " & Mytoken.SelectToken("submissionId").ToString & Environment.NewLine & Environment.NewLine
Dim arrray As JArray = JArray.Parse(Mytoken.SelectToken("acceptedDocuments").ToString)
For Each acceptedDocuments In arrray
TextBox2.Text = TextBox2.Text & "My uuid IS: " & acceptedDocuments.SelectToken("uuid").ToString & Environment.NewLine
TextBox2.Text = TextBox2.Text & "My longId IS: " & acceptedDocuments.SelectToken("longId").ToString & Environment.NewLine
TextBox2.Text = TextBox2.Text & "My internalId IS: " & acceptedDocuments.SelectToken("internalId").ToString & Environment.NewLine
TextBox2.Text = TextBox2.Text & "My hashKey IS: " & acceptedDocuments.SelectToken("hashKey").ToString & Environment.NewLine
Next
Related
I'm reading JSON responses from the Binance Api, from this link
I need to get some of the data out of it and this is the code I'm using:
Imports System.Net
Imports Newtonsoft.Json
Imports System.Collections.Generic
Public Class Form1
Private wc As New WebClient()
Private wc1 As New WebClient()
Private wc2 As New WebClient()
Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim btc = Await wc.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR")
Dim doge = Await wc1.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=DOGEEUR")
Dim bnb = Await wc2.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(btc)
Dim d1 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(doge)
Dim d2 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(bnb)
Label1.Text = "PRICE " + d("lastPrice")
Label2.Text = "24H CHANGE " + d("priceChange")
Label3.Text = "24H CHANGE % " + d("priceChangePercent")
Label4.Text = "HIGH 24H " + d("highPrice")
Label5.Text = "LOW 24H " + d("lowPrice")
Label6.Text = "PRICE " + d1("lastPrice")
Label7.Text = "24H CHANGE " + d1("priceChange")
Label8.Text = "24H CHANGE % " + d1("priceChangePercent")
Label9.Text = "HIGH 24H " + d1("highPrice")
Label10.Text = "LOW 24H " + d1("lowPrice")
Label11.Text = "PRICE " + d2("lastPrice")
Label12.Text = "24H CHANGE " + d2("priceChange")
Label13.Text = "24H CHANGE % " + d2("priceChangePercent")
Label14.Text = "HIGH 24H " + d2("highPrice")
Label15.Text = "LOW 24H " + d2("lowPrice")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Start()
End Sub
End Class
This code is working perfectly, the Timer.Intrval is set at 1000ms, but after a while I'm getting an exception:
System.NotSupportedException: WebClient does not support concurrent I/O operations
in the line:
Dim bnb = Await wc2.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
How can I solve it? It doesn't seems wrong cause I'm using 3 different WebClients objects to do that.
Also, how can I just display just 2 decimals after the comma ?
Since you have all async method to call, I suggest to move the API requests to an async method that, when initialized, keeps sending requests to the API - with a delay between calls - until the CancellationToken passed to the method signals that its time to quit.
I'm passing a Progress<T> delegate to the method, which is responsible to update the UI when the Tasks started by the aysnc method return their results.
The delegate of course executes in the UI Thread (here; anyway, the Thread that created and initialized it).
You can run this method from any other method / event handler that can be aysnc. Here, for example, the Click handler of a button. You can also start it from the Form.Load handler. Or whatever else.
I've decide to deserialize the JSON responses to a class model, since some values need to be converted to different types to make sense. As the Date/Time values returned, which are expressed in Unix (milliseconds) notation. So I'm using a custom UnixDateTimeConverter to convert the Date/Time values to DateTimeOffset structures.
Imports System.Net
Imports System.Net.Http
Imports System.Threading
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Converters
Private ctsBinance As CancellationTokenSource = Nothing
Private Async Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
ctsBinance = New CancellationTokenSource()
Dim progressReport = New Progress(Of BinanceResponseRoot())(AddressOf BinanceProgress)
Try
' Pass the Pogress<T> delegate, the delay in ms and the CancellationToken
Await DownLoadBinanceData(progressReport, 1000, ctsBinance.Token)
Catch tcEx As TaskCanceledException
Console.WriteLine("Tasks canceled")
Finally
ctsBinance.Dispose()
End Try
End Sub
Private Sub BinanceProgress(results As BinanceResponseRoot())
Console.WriteLine("PRICE " & results(0).LastPrice.ToString("N2"))
Console.WriteLine("24H CHANGE " & results(0).PriceChange.ToString("N2"))
Console.WriteLine("24H CHANGE % " & results(0).PriceChangePercent.ToString("N2"))
Console.WriteLine("HIGH 24H " & results(0).HighPrice.ToString("N2"))
Console.WriteLine("LOW 24H " & results(0).LowPrice.ToString("N2"))
Console.WriteLine("PRICE " & results(1).LastPrice.ToString("N2"))
Console.WriteLine("24H CHANGE " & results(1).PriceChange.ToString("N2"))
Console.WriteLine("24H CHANGE % " & results(1).PriceChangePercent.ToString("N2"))
Console.WriteLine("HIGH 24H " & results(1).HighPrice.ToString("N2"))
Console.WriteLine("LOW 24H " & results(1).LowPrice.ToString("N2"))
Console.WriteLine("PRICE " & results(1).LastPrice.ToString("N2"))
Console.WriteLine("24H CHANGE " & results(2).PriceChange.ToString("N2"))
Console.WriteLine("24H CHANGE % " & results(2).PriceChangePercent.ToString("N2"))
Console.WriteLine("HIGH 24H " & results(2).HighPrice.ToString("N2"))
Console.WriteLine("LOW 24H " & results(2).LowPrice.ToString("N2"))
End Sub
To cancel the execution of the Tasks, call the Cancel() method of the CancellationTokenSource. If the Tasks are not canceled before the Form / Window closes, call it when the Form / Window is closing, handling that event.
ctsBinance?.Cancel()
ctsBinance = Nothing
The worker method:
The method keeps running queries to the API in parallel until a cancellation is requested, calling the Cancel() method of the CancellationTokenSource.
I'm using a static HttpClient to send the API requests, since this is more likely its kind of job (no custom initialization, it uses all defaults: you may need to initialize a HttpClientHandler in some contexts, as specific Security Protocols).
All HttpClient.GetAsStringAsync() Tasks are added to a List(Of Task), then all Tasks are executed calling Task.WhenAll().
When all Tasks return, the API responses are deserialized to the BinanceResponseRoot model and the Progress<T> delegate is called to update the UI with the information received.
Private Shared binanceClient As New HttpClient()
Public Async Function DownLoadBinanceData(progress As IProgress(Of BinanceResponseRoot()),
delay As Integer, token As CancellationToken) As Task
While Not token.IsCancellationRequested
Dim tasks As New List(Of Task(Of String))({
binanceClient.GetStringAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR"),
binanceClient.GetStringAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=DOGEEUR"),
binanceClient.GetStringAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
})
Await Task.WhenAll(tasks)
Dim btcEur = JsonConvert.DeserializeObject(Of BinanceResponseRoot)(tasks(0).Result)
Dim dogeEur = JsonConvert.DeserializeObject(Of BinanceResponseRoot)(tasks(1).Result)
Dim bnbEur = JsonConvert.DeserializeObject(Of BinanceResponseRoot)(tasks(2).Result)
progress.Report({btcEur, dogeEur, bnbEur})
Await Task.Delay(delay, token)
End While
End Function
Class Model to convert that JSON data to the corresponding .Net Type values:
Public Class BinanceResponseRoot
Public Property Symbol As String
Public Property PriceChange As Decimal
Public Property PriceChangePercent As Decimal
Public Property WeightedAvgPrice As Decimal
Public Property PrevClosePrice As Decimal
Public Property LastPrice As Decimal
Public Property LastQty As Decimal
Public Property BidPrice As Decimal
Public Property BidQty As Decimal
Public Property AskPrice As Decimal
Public Property AskQty As Decimal
Public Property OpenPrice As Decimal
Public Property HighPrice As Decimal
Public Property LowPrice As Decimal
Public Property Volume As Decimal
Public Property QuoteVolume As Decimal
<JsonConverter(GetType(BinanceDateConverter))>
Public Property OpenTime As DateTimeOffset
<JsonConverter(GetType(BinanceDateConverter))>
Public Property CloseTime As DateTimeOffset
Public Property FirstId As Long
Public Property LastId As Long
Public Property Count As Long
End Class
Friend Class BinanceDateConverter
Inherits UnixDateTimeConverter
Public Overrides Function CanConvert(t As Type) As Boolean
Return t = GetType(Long) OrElse t = GetType(Long?)
End Function
Public Overrides Function ReadJson(reader As JsonReader, t As Type, existingValue As Object, serializer As JsonSerializer) As Object
Dim uxDT As Long? = serializer.Deserialize(Of Long?)(reader)
Return DateTimeOffset.FromUnixTimeMilliseconds(uxDT.Value)
End Function
Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
Dim dtmo = DirectCast(value, DateTimeOffset)
If dtmo <> DateTimeOffset.MinValue Then
serializer.Serialize(writer, CType(DirectCast(value, DateTimeOffset).ToUnixTimeMilliseconds(), ULong))
Else
MyBase.WriteJson(writer, Nothing, serializer)
End If
End Sub
End Class
1000ms is probably too fast, the wc2.DownloadStringTaskAsync task is probably not finished. You can Stop your timer before starting those download tasks and Start it again when the tasks are done:
Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Stop
Dim downloadTasks As New List(Of Task(Of String))
Dim btc = wc.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR")
Dim doge = wc1.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=DOGEEUR")
Dim bnb = wc2.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
downloadTasks.Add(btc)
downloadTasks.Add(doge)
downloadTasks.Add(bnb)
Await Task.WhenAll(downloadTasks)
Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(btc.Result)
Dim d1 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(doge.Result)
Dim d2 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(bnb.Result)
Label1.Text = "PRICE " + d("lastPrice")
Label2.Text = "24H CHANGE " + d("priceChange")
Label3.Text = "24H CHANGE % " + d("priceChangePercent")
Label4.Text = "HIGH 24H " + d("highPrice")
Label5.Text = "LOW 24H " + d("lowPrice")
Label6.Text = "PRICE " + d1("lastPrice")
Label7.Text = "24H CHANGE " + d1("priceChange")
Label8.Text = "24H CHANGE % " + d1("priceChangePercent")
Label9.Text = "HIGH 24H " + d1("highPrice")
Label10.Text = "LOW 24H " + d1("lowPrice")
Label11.Text = "PRICE " + d2("lastPrice")
Label12.Text = "24H CHANGE " + d2("priceChange")
Label13.Text = "24H CHANGE % " + d2("priceChangePercent")
Label14.Text = "HIGH 24H " + d2("highPrice")
Label15.Text = "LOW 24H " + d2("lowPrice")
Timer1.Start
End Sub
That way you will be sure the previous download has completed.
You can also check if the WebClient is still busy using the WebClient.IsBusy property before starting another download.
As far as displaying 2 decimals, take a look at Strings.FormatNumber. You can specify a NumDigitsAfterDecimal parameter that indicates
how many places are displayed to the right of the decimal. The default value is -1, which indicates that the computer's regional settings are used.
I'm working with a coworker's code trying to recreate his REST web service in a console application. I'm very new to web services and VB so it's been quite difficult for me. It will work fine on his but I keep getting an Internal Server Error (500). I have looked this up and some suggestions I found were changing "POST" to "GET" but I received "Cannot get content body with this verb-type". I've seen forums about something like this not working from another person's machine. My coworker and I have tried going through it over and over but getting the same results.
This is the Console App
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Reflection
Imports System.Text
Imports System.Threading.Tasks
Imports System.Web
Imports System.Web.UI
Imports System.Xml
Module RestConsoleClient
Private req As HttpWebRequest = Nothing
Private res As HttpWebResponse = Nothing
Private responseText As String = ""
Sub Main(args As String())
Dim url As String = ""
Try
If args.Count < 1 OrElse String.IsNullOrEmpty(args(0)) Then
Console.WriteLine("Endpoint Address is required as commandline argument;" _
& vbCrLf & "Copy/Paste one of the endpoint addresses from My.Settings into the Debug commandline arguments section" _
& vbCrLf & vbCrLf & "Press ENTER to start over...")
Console.ReadKey()
Return
Else
url = args(0)
End If
req = CType(WebRequest.Create(url), HttpWebRequest)
req.Method = "POST"
'** The conditions below allowed for generic raw data to be input as text vs. processing input data as a json object.
'** These conditions became redundant with the addition of config for WebContentTypeMapper and corresponding class to accept
'** a post declared with application/json ContentType as generic raw data, and then SUBSEQUENTLY de/serialize the json data as necessary
'If url.Contains("streamweaver") Then
' req.ContentType = "text"
'ElseIf url.Contains("auth") Then
' req.ContentType = "application/json" '; charset=utf-8"
'Else
' 'No other options are yet determined
'End If
req.Timeout = 30000
Dim sJson As String = "{""Name"":""Ashu"",""Age"":""29"",""Exp"":""7 Years"",""Technology"":"".NET""}"
Dim postBytes = Encoding.UTF8.GetBytes(sJson)
req.ContentLength = postBytes.Length
Dim requestStream As Stream = req.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
res = CType(req.GetResponse(), HttpWebResponse)
' I retained the basics for response reception even though it was not integral to this test
Dim responseStream As Stream = res.GetResponseStream()
Dim streamReader = New StreamReader(responseStream)
responseText = streamReader.ReadToEnd()
Console.WriteLine("HTTP Response: " & res.StatusCode & " - " & res.StatusDescription.Trim)
Console.WriteLine("[ Response Data: " & responseText.Trim & " ]")
Console.ReadKey()
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.ReadKey()
End Try
End Sub
End Module
This here is the Interface
Imports System.IO
Imports System.ServiceModel
Imports System.ServiceModel.Web
<ServiceContract> _
Public Interface IRestServiceImpl
'<OperationContract> _
'<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Xml, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="xml/{id}")> _
'Function XMLData(id As String) As String
'<OperationContract> _
'<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="json/{id}")> _
'Function JSONData(id As String) As String
<OperationContract> _
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, RequestFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Bare, UriTemplate:="auth")> _
Function Auth(rData As Stream) As ResponseData
<OperationContract> _
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, RequestFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Bare, UriTemplate:="streamweaver")> _
Function StreamWeaver(sData As Stream) As String
End Interface
And here is the class
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Security.AccessControl
Imports System.Text
Imports Newtonsoft.Json
Public Class RestServiceImpl
Implements IRestServiceImpl
Private filePathOnServer As String = My.Settings.OutputFolder
'Public Function XMLData(id As String) As String Implements IRestServiceImpl.XMLData
' Return "You requested product " & id
'End Function
'Public Function JSONData(id As String) As String Implements IRestServiceImpl.JSONData
' Return "You requested product " & id
'End Function
Public Function Auth(request As Stream) As ResponseData Implements IRestServiceImpl.Auth
Dim streamReader = New StreamReader(request)
Dim requestText As String = streamReader.ReadToEnd()
Dim rData As RequestData = JsonConvert.DeserializeObject(Of RequestData)(requestText)
Dim response = New ResponseData() With { _
.Name = rData.Name, _
.Age = rData.Age, _
.Exp = rData.Exp, _
.Technology = rData.Technology _
}
Dim fileOutput As String = "As of " & DateTime.Now & ", " _
& response.Name.Trim & " is a person who is " _
& response.Age.Trim & " years old, having " _
& response.Exp.Trim & " of experience with " _
& response.Technology.Trim & " technology."
Console.SetError(New StreamWriter("C:\Users\apearson\Documents\Eureka.txt"))
Console.[Error].WriteLine(fileOutput)
Console.[Error].Close()
Dim ctx As WebOperationContext = WebOperationContext.Current
If rData IsNot Nothing Then
ctx.OutgoingResponse.StatusCode = Net.HttpStatusCode.Accepted
Else
ctx.OutgoingResponse.StatusCode = Net.HttpStatusCode.NotAcceptable
End If
Return response
End Function
Public Function StreamWeaver(reqData As Stream) As String Implements IRestServiceImpl.StreamWeaver
StreamWeaver = Nothing
Dim ctx As WebOperationContext = WebOperationContext.Current
If reqData IsNot Nothing Then
ctx.OutgoingResponse.StatusCode = Net.HttpStatusCode.Accepted
Else
ctx.OutgoingResponse.StatusCode = Net.HttpStatusCode.NotAcceptable
End If
Dim streamReader As StreamReader = New StreamReader(reqData)
StreamWeaver = streamReader.ReadToEnd()
Console.SetError(New StreamWriter(filePathOnServer.Trim & "\RestServiceJSONRaw.txt"))
Console.[Error].WriteLine(DateTime.Now & ": " & vbCrLf & StreamWeaver.Trim)
Console.[Error].Close()
Return StreamWeaver
End Function
End Class
If there is anymore information needed, let me know. Again, this is kind of new to me.
I am having a troble parsing JSON using vb.net with Newtonsoft Json library.
My JSON Data is as follows :
{
"Result":"Success",
"UserID":"johns",
"Password":null,
"Locked":"False",
"Comment":"",
"LastLoggedOn":"11/9/2013 9:14:17 PM",
"NumFailedAttempts":"1",
"FirstName":"John",
"LastName":"Smith",
"MessageNum":"UA-000",
"MessageText":"Authorisation successful"
}
My code is as follows :
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(strJSONEncode)
Response.Write(a.ToString)
Response.Write(a.MessageText)
This does not produce any output.
Any help is appreciated.
Assuming your saLoginResponse class is defined like the following, and your strJSONEncode string contains the JSON data you posted in your question, your code should work fine.
Public Class saLoginResponse
Public Property Result As String
Public Property UserID As String
Public Property Password As String
Public Property Locked As Boolean
Public Property Comment As String
Public Property LastLoggedOn As String
Public Property NumFailedAttempts As String
Public Property FirstName As String
Public Property LastName As String
Public Property MessageNum As String
Public Property MessageText As String
End Class
Demo:
Sub Main()
Dim json As String = _
"{" + _
"""Result"":""Success""," + _
"""UserID"":""johns""," + _
"""Password"":null," + _
"""Locked"":""False""," + _
"""Comment"":""""," + _
"""LastLoggedOn"":""11/9/2013 9:14:17 PM""," + _
"""NumFailedAttempts"":""1""," + _
"""FirstName"":""John""," + _
"""LastName"":""Smith""," + _
"""MessageNum"":""UA-000""," + _
"""MessageText"":""Authorisation successful""" + _
"}"
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(json)
Debug.WriteLine(a.MessageText + " for " + a.FirstName + " " + a.LastName)
End Sub
Output in debug window:
Authorisation successful for John Smith
I need to filter where clause in my GetProduct function using http request query string property. I have set up my filters in urls. (eg burgers.aspx?filter=burgers'). Burgers is the name of database table category(Where ProductCat = filter). I understand I need to pass parameter to interaction class because it does not handle requests. Please help.
Interaction class:
Public Class Interaction
Inherits System.Web.UI.Page
' New instance of the Sql command object
Private cmdSelect As New SqlCommand
' Instance of the Connection class
Private conIn As New Connection
Region "Menu functions and subs"
' Set up the SQL statement for finding a Product by ProductCat
Private Sub GetProduct(ByVal CatIn As String)
' SQL String
Dim strSelect As String
strSelect = "SELECT * "
strSelect &= " FROM Menu "
strSelect &= " WHERE ProductCat = "
strSelect &= "ORDER BY 'ProductCat'"
' Set up the connection to the datebase
cmdSelect.Connection = conIn.Connect
' Add the SQL string to the connection
cmdSelect.CommandText = strSelect
' Add the parameters to the connection
cmdSelect.Parameters.Add("filter", SqlDbType.NVarChar).Value = CatIn
End Sub
'Function to create list of rows and columns
Public Function ReadProduct(ByVal CatIn As String) As List(Of Dictionary(Of String, Object))
'Declare variable to hold list
Dim ReturnProducts As New List(Of Dictionary(Of String, Object))
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
'Get number of columns in current row
Dim FieldCount = dbr.FieldCount()
Dim ColumnList As New List(Of String)
'Loop through all columns and add to list
For i As Integer = 0 To FieldCount - 1
ColumnList.Add(dbr.GetName(i))
Next
While dbr.Read()
'Declare variable to hold list
Dim ReturnProduct As New Dictionary(Of String, Object)
'Loop through all rows and add to list
For i As Integer = 0 To FieldCount - 1
ReturnProduct.Add(ColumnList(i), dbr.GetValue(i).ToString())
Next
'Add to final list
ReturnProducts.Add(ReturnProduct)
End While
cmdSelect.Parameters.Clear()
'Close connection
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return ReturnProducts
End Function
Code Behind:
Partial Class Burger
Inherits System.Web.UI.Page
'String Used to build the necessary markup and product information
Dim str As String = ""
''Var used to interact with SQL database
Dim db As New Interaction
' New instance of the Sql command object
Private cmdSelect As New SqlCommand
' Instance of the Connection class
Private conIn As New Connection
Protected Sub printMenuBlock(ByVal productName As String)
'Set up variable storing the product and pull from databse
Dim product = db.ReadProduct(productName)
'Add necessary markup to str variable, with products information within
For i As Integer = 0 To product.Count - 1
str += "<div class='menuItem'>"
'str += " <img alt='Item Picture' class='itemPicture' src='" + product(i).ImagePath.Substring(3).Replace("\", "/") + "' />"
str += " <div class='itemInfo'>"
str += " <h1 class='itemName'>"
str += " " + product(i).Item("ProductName") + "</h1>"
'str += " <h3 class='itemDescription'>"
str += " " + product(i).Item("ProductDescription")
str += " <h1 class ='itemPrice'>"
str += " " + product(i).Item("ProductPrice") + "</h1>"
str += " "
str += " </div>"
str += " </div>"
Next
End Sub
''Uses
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Dim v = Request.QueryString("filter")
'Response.Write("filter is")
'Response.Write(v)
Dim value = Request.QueryString("filter")
'Get string from printMenuBlock method
printMenuBlock(str)
'Print the str variable in menuPlace div
menuPlace.InnerHtml = str
End Sub
End Class
I need a direction on how to pass the Request.QueryString("filter") to GetProduct function to filter by page according to ProductCategory. Thanks in advance.
Try something like this:
Dim filter = Request.QueryString("filter")
Dim sqlStr = "Select * From menu Where ProductCat = #filter Order By ProductCat"
cmdSelect.Parameters.Add("filter", SqlDbType.NVarChar).Value = filter
I look for a solution to my problem since 2 weeks without solution.
I would like to deserialize JSON with JSON.NET, but noway ...
I create class but when i deserialize the object stay empty (Nothing).
Here the JSON :
{"plannifReponse":
{"#competence":"Abonnement","plannifDonnees":
{"entry":
[
{"key":"2013-8-11T00:00","value":
{"creneaux":
[
{"#jour":"2013-8-11T00:00","#heure":"09","#minute":"30","nombreRessources":10},
{"#jour":"2013-8-11T00:00","#heure":"10","#minute":"30","nombreRessources":2},
{"#jour":"2013-8-11T00:00","#heure":"17","#minute":"30","nombreRessources":5},
{"#jour":"2013-8-11T00:00","#heure":"20","#minute":"30","nombreRessources":5},
{"#jour":"2013-8-11T00:00","#heure":"21","#minute":"00","nombreRessources":16}
]
}
},
{"key":"2013-7-30T00:00","value":
{"creneaux":
[{"#jour":"2013-7-30T00:00","#heure":"12","#minute":"00","nombreRessources":4},{"#jour":"2013-7-30T00:00","#heure":"12","#minute":"15","nombreRessources":10},{"#jour":"2013-7-30T00:00","#heure":"12","#minute":"30","nombreRessources":3},{"#jour":"2013-7-30T00:00","#heure":"14","#minute":"00","nombreRessources":8},{"#jour":"2013-7-30T00:00","#heure":"18","#minute":"30","nombreRessources":10}]}}]}}}
For this i translate with that Class:
Public Class plannifReponse
Public competence As String
Public plannifDonnees As Dictionary(Of String, ListCreneaux)
End Class
Public Class ListCreneaux
Public listCreneaux() As Creneau
End Class
Public Class Creneau
Public jour As String
Public heure As String
Public minute As String
Public nombreRessources As Integer
Public Sub New(ByVal _jour, ByVal _heure, ByVal _minute, ByVal _nombreRessources)
jour = _jour
heure = _heure
minute = _minute
nombreRessources = _nombreRessources
End Sub
End Class
And the code :
Dim prev As plannifReponse = JsonConvert.DeserializeObject(Of plannifReponse)(My_dispos)
But it doesn't work, no error message, but prev stay "Nothing"
For help, here the source object use to serialise (it is on Java)
public class OutputPlannif {
private String competence;
private HashMap<String, ListCreneaux> plannifDonnees;
}
public class ListCreneaux {
private ArrayList<Creneau> listCrenaux;
}
public class Creneau {
private String jour;
private String heure;
private String minute;
private int nombreRessources;
}
If anyone have an idea...
Thanks
Matt
You should create a series of classes which map the JSON you want to deserialize. There are tools (such as this one) which can do that for you. Or you can do it by hand, taking one member at a time, with the result shown below:
Public Class StackOverflow_17956746
Public Class OutputPlannif
<JsonProperty("plannifReponse")> _
Public PlannifReponse As PlannifReponse
End Class
Public Class PlannifReponse
<JsonProperty("#competence")> _
Public Competence As String
<JsonProperty("plannifDonnees")> _
Public PlannifDonnees As PlannifDonnees
End Class
Public Class PlannifDonnees
<JsonProperty("entry")> _
Public Entries As List(Of Entry)
End Class
Public Class Entry
<JsonProperty("key")> _
Public Key As String
<JsonProperty("value")> _
Public Value As Value
End Class
Public Class Value
<JsonProperty("creneaux")> _
Public ListCreneaux As List(Of Creneau)
End Class
Public Class Creneau
<JsonProperty("#jour")> _
Public Jour As String
<JsonProperty("#heure")> _
Public Heure As String
<JsonProperty("#minute")> _
Public Minute As String
<JsonProperty("nomberRessources")> _
Public NombreRessources As Integer
End Class
Const JSON As String = "{" & vbCrLf & _
" ""plannifReponse"":" & vbCrLf & _
"{""#competence"":""Abonnement"",""plannifDonnees"":" & vbCrLf & _
"{""entry"":" & vbCrLf & _
"[" & vbCrLf & _
"{""key"":""2013-8-11T00:00"",""value"":" & vbCrLf & _
"{""creneaux"":" & vbCrLf & _
"[" & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""09"",""#minute"":""30"",""nombreRessources"":10}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""10"",""#minute"":""30"",""nombreRessources"":2}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""17"",""#minute"":""30"",""nombreRessources"":5}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""20"",""#minute"":""30"",""nombreRessources"":5}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""21"",""#minute"":""00"",""nombreRessources"":16}" & vbCrLf & _
"]" & vbCrLf & _
"}" & vbCrLf & _
"}," & vbCrLf & _
"{""key"":""2013-7-30T00:00"",""value"":" & vbCrLf & _
"{""creneaux"":" & vbCrLf & _
"[{""#jour"":""2013-7-30T00:00"",""#heure"":""12"",""#minute"":""00"",""nombreRessources"":4},{""#jour"":""2013-7-30T00:00"",""#heure"":""12"",""#minute"":""15"",""nombreRessources"":10},{""#jour"":""2013-7-30T00:00"",""#heure"":""12"",""#minute"":""30"",""nombreRessources"":3},{""#jour"":""2013-7-30T00:00"",""#heure"":""14"",""#minute"":""00"",""nombreRessources"":8},{""#jour"":""2013-7-30T00:00"",""#heure"":""18"",""#minute"":""30"",""nombreRessources"":10}]}}]}}}"
Public Shared Sub Test()
Dim output As OutputPlannif
output = JsonConvert.DeserializeObject(Of OutputPlannif)(JSON)
Console.WriteLine(output)
End Sub
End Class