How to convert string to json vb.net - json

this is the code i have, dim sline from string to json, i have try it and search on google, but i havent done yet...
please help
Dim sURL As String
sURL = TextBox1.Text
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
Dim myProxy As New WebProxy("myproxy", 80)
myProxy.BypassProxyOnLocal = True
wrGETURL.Proxy = myProxy
wrGETURL.Proxy = WebProxy.GetDefaultProxy()
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream()
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
Dim i As Integer = 0
Do While Not sLine Is Nothing
i += 1
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
Console.WriteLine("{0}:{1}", i, sLine)
End If
Loop
Dim respon As Array = sLine.ToArray()
Console.ReadLine()
Console.WriteLine(respon("traceNo"))
Console.ReadLine()
i want to convert the Dim sline to json, how it possible?

Newtonsoft.JSON is a VERY handy NuGet to easy use JSON in VB.Net.
Seperate your lines into a List(Of Integer, String) (i,sLine)
and Serialize it with
Dim yourJSONString = JsonConvert.SerializeObject(yourList)

Related

How can I handle parsed JSON property/value not existing in VB.Net?

I shall get to the point and it is probably an easy answer for someone. The JSON being returned from HubSpot may or may not include a property such as phone and address because it is not filled out in HubSpot. This causes an error in the For Each block below:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=HubSpotGetAllCompanies
How can I handle it so that if there is no property for telephone for example, I can put in a DBNull value instead.
Thanks in advance!
Imports System.ComponentModel
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Module Index
Sub Main()
Dim counter = 0
Dim offset As String = String.Empty
Dim hasmore As Boolean = False
Dim hapikey = "xxx"
Dim hubSpot As New Dal.HubSpot.Pull
'Create Table
Dim companiesTable As DataTable = New DataTable()
companiesTable.Columns.Add("PortalID")
companiesTable.Columns.Add("CompanyID")
companiesTable.Columns.Add("Company")
companiesTable.Columns.Add("Website")
companiesTable.Columns.Add("Address1")
companiesTable.Columns.Add("City")
companiesTable.Columns.Add("Country")
companiesTable.Columns.Add("Postcode")
companiesTable.Columns.Add("Telephone")
companiesTable.Columns.Add("Ref")
companiesTable.Columns.Add("VatCode")
'Create Values
'Loop as you can only return so many companies at once (250 is limit I believe)
Do
Dim url As String = String.Format("https://api.hubapi.com/companies/v2/companies/paged?hapikey={0}&properties=name&properties=website&properties=address&properties=city&properties=country&properties=zip&properties=phone&limit=10{1}", hapikey, offset)
Dim httpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
httpWebRequest.ContentType = "application/json"
httpWebRequest.Method = "GET"
Dim httpResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
Using streamReader = New StreamReader(httpResponse.GetResponseStream())
Dim result = streamReader.ReadToEnd()
Dim jObject As JObject = JObject.Parse(result)
Dim jhasmore As JToken = jObject("has-more")
Dim joffset As JToken = jObject("offset")
Dim jcompanies As JToken = jObject("companies")
If jhasmore.ToString().ToLower() = "true" Then
hasmore = True
Else
hasmore = False
End If
offset = String.Format("&offset={0}", joffset.ToString())
For Each item In jcompanies.ToList()
Dim portalId = item("portalId").ToString()
Dim companyId = item("companyId").ToString()
Dim company = item("properties")("name")("value").ToString()
Dim website = If(item("properties")("website")("value").ToString(), DBNull.Value)
Dim address1 = If(item("properties")("address")("value").ToString(), DBNull.Value)
Dim city = If(item("properties")("city")("value").ToString(), DBNull.Value)
Dim country = If(item("properties")("country")("value").ToString(), DBNull.Value)
Dim postcode = If(item("properties")("zip")("value").ToString(), DBNull.Value)
Dim telephone = If(item("properties")("phone")("value").ToString(), DBNull.Value)
Dim ref = DBNull.Value
Dim vatCode = DBNull.Value
companiesTable.Rows.Add(portalId, companyId, company, website, address1, city, country, postcode, telephone, ref, vatCode)
Next
End Using
counter += 1
Loop While hasmore
hubSpot.GetAllHubSpotCompanies(companiesTable)
End Sub
Try using the Null Propagation Operator ? between any token accessors that may not be filled:
Dim telephone = If(item("properties")("phone")?("value").ToString(), DBNull.Value)
If a particular token is Nothing, it will return Nothing to the If and set the variable to DBNull.Value

I am always getting fingerprint not verified

Anytime I scan a fingerprint for verification I get the message "Fingerprint not verified" even though I have already enrolled that fingerprint into the database. Here is the code for capture when the form loads
Here is the code for capture when the form loads
Private Sub Me_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Init()
StartCapture()
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim sql As String
conn.ConnectionString = "**** "
conn.Open()
sql = ("SELECT * FROM new_case_file")
cmd.Connection = conn
cmd.CommandText = sql
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
While (rdr.Read())
Dim MemStream As IO.MemoryStream
Dim fpBytes As Byte()
fpBytes = rdr("FingerPrint")
MemStream = New IO.MemoryStream(fpBytes)
Dim templa8 As DPFP.Template = New DPFP.Template()
templa8.DeSerialize(MemStream)
Dim serializedTemplate As Byte() = MemStream.ToArray
Dim tmpObj As New AppData
Dim FPList As List(Of AppData) = New List(Of AppData)
'tmpObj.No = rdr("No").ToString()
'tmpObj.Template = templa8
'FPList.Add(tmpObj)
End While
conn.Close()
End Sub
Here is the code for verification. When l click on the button it should verify, because l called the sub verifyControl_Commplete in the button click sub.
Private Sub verifyControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As
DPFP.Gui.EventHandlerStatus) Handles verifyControl.OnComplete
Dim printFound As Boolean = False
'Dim printFound As Boolean = True
'Dim printFound As Boolean = False
Dim VerifiedFPData = New AppData
Dim FPList As List(Of AppData) = New List(Of AppData)
Try
For Each FPData As AppData In FPList
Dim tmplateData As New DPFP.Template
'tmplateData = FPData.Template
Dim compareTo As New DPFP.FeatureSet
compareTo = FeatureSet
Dim ver As New DPFP.Verification.Verification()
Dim res As New DPFP.Verification.Verification.Result()
If Not tmplateData Is Nothing Then
ver.Verify(FeatureSet, tmplateData, res)
If res.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
printFound = True
VerifiedFPData = FPData
Exit For
End If
End If
Next
Catch ex As Exception
MessageBox.Show("Error")
End Try
If printFound Then
MsgBox("Verified")
Else
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
MsgBox("Not Verified")
End If
End Sub
Private Sub btnverifyfp_Click(sender As Object, e As EventArgs) Handles btnverifyfp.Click
verifyControl_OnComplete(Nothing, Nothing, Nothing)
End Sub
This is the code l used in saving the fingerprint
Dim fingerprintData As MemoryStream = New MemoryStream
Enroller.Template.Serialize(fingerprintData)
Dim serializedTemplate As Byte() = fingerprintData.ToArray()
Dim bytes() As Byte = serializedTemplate
Try this:
'THIS NEEDS TO BE AT THE CLASS-LEVEL, AS A MEMBER
Private FPList As New List(Of AppData)
Private Sub Me_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs)
Handles MyBase.Load
Init()
StartCapture()
Dim sql As String = "SELECT * FROM new_case_file"
Using conn As New MySqlConnection("**** "), _
cmd As New MySqlCommand(sql, conn)
conn.Open()
Using rdr As MySqlDataReader = cmd.ExecuteReader()
FPList.Clear()
While (rdr.Read())
Dim tmpObj As New AppData
tmpObj.No = rdr("No").ToString()
Dim fpBytes As Byte() = rdr("FingerPrint")
Using MemStream As New IO.MemoryStream(fpBytes)
Dim templa8 As New DPFP.Template()
templa8.DeSerialize(MemStream)
End Using
tmpObj.Template = templa8
FPList.Add(tmpObj)
End While
rdr.Close()
End Using
End Using
End Sub
And now other code later can use that same FPList variable. If you find yourself writing New List(Of AppData) anywhere else, you're doing something wrong.
The AppData class should look something like this:
Public Class AppData
Public Property No As String
Public Property Template As DFFP.Template
End Class
And finally, the verify code:
Private Sub verifyControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet,
ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus)
Handles verifyControl.OnComplete
Try
Dim ver As New DPFP.Verification.Verification()
Dim res As New DPFP.Verification.Verification.Result()
For Each FPData As AppData In FPList
If FPData.Template Is Nothing Then Continue
ver.Verify(FeatureSet, FPData.Template, res)
If res.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
MsgBox("Verified")
Return
End If
Next FPDAta
Catch ex As Exception
MessageBox.Show("Error")
End Try
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
MsgBox("Not Verified")
End Sub
Again... we don't have access to your API documentation, test data, or equipment. That means we're blind trying to help you here. There's probably some things wrong with this, and you'll have to be able to troubleshoot and debug.

How to parse json and read in vb.net

I have this code in my project:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = rawresp
and TextBox2 gets the JSON code correctly.
and this is my JSON code example:
{
"id":174543706,
"first_name":"Hamed",
"last_name":"Ap",
"username":"hamed_ap",
"type":"private"
}
My question:
How to get 174543706 from JSON code ("id") into TextBox3.Text???
You could use JavaScriptSerializer which is in System.Web.Script.Serialization.
Imports System.Web.Script.Serialization
Module Module1
Sub Main()
Dim s As String
Try
Dim rawresp As String = "{""id"":174543706,""first_name"":""Hamed"",""last_name"":""Ap"",""username"":""hamed_ap"",""type"":""private""}"
Dim jss As New JavaScriptSerializer()
Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(rawresp)
s = dict("id")
Catch ex As Exception
End Try
End Sub
End Module
try this code :
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(rawresp)
Dim firstItem = jsonResulttodict.item ("id")
hope it help you !!
How to get 174543706 from JSON code ("id") into TextBox3.Text?
{
"id": 174543706,
"first_name": "Hamed",
"last_name": "Ap",
"username": "hamed_ap",
"type": "private"
}
Sorry if my reply was late. I hope my answer can help someone who's still confused.
So what you do was get the response and read the JSON.
After you do ReadToEnd():
Dim xr As XmlReader = XmlReader.Create(New StringReader(rawresp))
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(rawresp)
Then What you need to do is to read the data from the response. you do like this:
Dim res As String = JsonConvert.SerializeXmlNode(doc)
Dim ThisToken As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(res)
Dim response As String = ThisToken("response").ToString()
Dim ThisData As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(response)
After that yo can get the data from the response and convert it into string
Dim idx As String = ThisData("id").ToString()
// the value of idx will be: 174543706
Then last you can put it into Texbox3.Text.
JSON can be parsed using adding Newtonsoft.Json.dll reference
Code :
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim json As String = New System.Net.WebClient().DownloadString("http://time.jsontest.com/")
Dim parsejson As JObject = JObject.Parse(json)
Dim thedate = parsejson.SelectToken("date").ToString()
txt1.Text = "Date Is "+thedate
End Sub
End Class
Reference : Narendra Dwivedi - Parse JSON
This works:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = JObject.Parse(rawresp)("id")

VB.NET - Convert Json to Xml using Json.NET

Is there any possible way to convert direct url to json into xml as text into one textbox?
Example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Json1 as string = "http://pastebin.com/raw.php?i=p3uBzBtm"
Dim jss = New JsonSerializer()
Dim response2 = jss.Deserialize(Of Object)(Json1)
textbox1.text = response2
End Sub
Sorry for this bad example, I'm newbie in this language.
Use this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Json1 As String = New WebClient().DownloadString("http://pastebin.com/raw.php?i=p3uBzBtm")
Dim str = JsonConvert.DeserializeXmlNode(Json1)
TextBox1.Text = str.OuterXml
End Sub
For multiple nodes you will want something like this:
Dim Json1 As String = "{ 'root': " & New WebClient().DownloadString("http://pastebin.com/raw.php?i=ugZrw4d6") & " }"
Dim doc As XmlDocument = JsonConvert.DeserializeXmlNode(Json1)
Dim result As String = doc.ChildNodes(0).InnerXml
TextBox1.Text = result

De-serializing JSON data in vb

I have been trying to deserialize JSON data, and this is how far I have gotten before searching StackOverflow and I followed an article however it still broke. I'm getting a runtime error on this line:
Dim jsonObject As Newtonsoft.Json.Linq.JArray = JsonConvert.DeserializeObject(json)
Stating "Can not convert Object to String."
Thanks in advance :D
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Structure JSONList
Dim URL, Name As String
End Structure
Public Class Form1
Dim JSONList As List(Of ListViewItem)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim request As WebRequest = WebRequest.Create("http://www.reddit.com/r/EarthPorn.json")
Dim response As WebResponse = request.GetResponse()
' Get the stream containing content returned by the server.
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
MessageBox.Show(responseFromServer)
Dim json As String = responseFromServer
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim jsonObject As Newtonsoft.Json.Linq.JArray = JsonConvert.DeserializeObject(json)
Dim JSONDecode() As JSONList = (From j In jsonObject
Select New JSONList() With {.URL = j("URL"),
.Name = j("Name")}
).ToArray()
MessageBox.Show(JSONDecode(0).Name)
End Sub
End Class