How to deserialize json in VB.Net - json

I have a JSON that I want to deserialize.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim client As New RestClient(BaseUrl)
Dim Respons As Object
client.Authenticator = OAuth1Authenticator.ForProtectedResource(PublicKey, PrivateKey, Token, TokenSecret)
Dim request As New RestRequest("xml/devices/list", Method.Get)
Respons = client.Execute(request)
Console.WriteLine(Respons.Content)
Console.ReadLine()
Dim request2 As New RestRequest("json/sensor/history?id=1556402310&IncludeUnit=1&InculdeHumanReadableDate=1", Method.Get)
Respons = client.Execute(request2)
Console.WriteLine(Respons.Content)
Console.ReadLine()
End Sub
So the JSON is in Respons, but I haven't a clue how to deserialize it
Have not done anything because I don't know how.
This is how the JSON looks like

Something like this:
Public Class Sensor_class
Public Property thing As Integer
Public Property thing2 As Object
Public Property results As Result()
End Class
Dim o as Sensor_class
o = JsonConvert.DeserializeObject(Of Sensor_class)(Respons.Content)

Related

VB .NET JSON Deserialization

I'm having a problem with JSON deserialization hope you can help me.
I have a JSON that have the following information:
{
"object":"list",
"more":false,
"data":[
{
"object":"number",
"id":"1",
"code":"1",
"name":"One",
},
{
"object":"number",
"id":"2",
"code":"2",
"name":"Two",
}
...
So I've a created a simple app so I can use that information:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim uri As New Uri(uriString)
'Make Request
Dim Request As HttpWebRequest = HttpWebRequest.Create(uri)
Request.Method = "GET"
'Get Response
Dim Response As HttpWebResponse = Request.GetResponse()
'Read Response
Dim Read = New StreamReader(Response.GetResponseStream())
Dim Raw As String = Read.ReadToEnd()
'Convert response
Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(Raw)
For Each item In dict
MsgBox(item)
MsgBox(item("code"))
TextBox1.Text += item("code").ToString + " - " + item("name").ToString + vbNewLine
Next
End Sub
It seems I get the response, since the Read I get the JSON, but after that, I can't get the information listed in that JSON. What I'm doing wrong?
You are not de-serializing properly. Your dict is empty like that.
This will work as intended.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim Request As HttpWebRequest = WebRequest.Create(New Uri(uriString))
Dim JSON_Response As String = New StreamReader(Request.GetResponse().GetResponseStream()).ReadToEnd()
Dim JSON_Obj1 As Object = New JavaScriptSerializer().DeserializeObject(JSON_Response)
Dim Test1 as String = JSON_Obj1("data")(0)("code")
For Each item In JSON_Obj1("data")
Debug.Print(item("code"))
Next
End Sub

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

Error While serializing object to json format using JsonConvert.SerializeObject function

I have a method to serialize object to json format. the object contains nested objects and lists. but i face this error :
Error getting value from 'Length' on 'Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter'.
Dim serilaize As New JsonSerializerSettings()
With serilaize
.PreserveReferencesHandling = PreserveReferencesHandling.Objects
End With
Dim strProgram As String = JsonConvert.SerializeObject(ProgramObject, Formatting.Indented, serilaize)
Any help please !
Thanks
This works:
Module Module1
Sub Main()
Dim ProgramObject = New TestObject()
ProgramObject.Items = New List(Of String)
ProgramObject.Items.Add("testitem")
Dim serialize As New Newtonsoft.Json.JsonSerializerSettings()
With serialize.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects
Dim strProgram As String = Newtonsoft.Json.JsonConvert.SerializeObject(ProgramObject, Newtonsoft.Json.Formatting.Indented, serialize)
End With
End Sub
End Module
TestObject looks like this:
Public Class TestObject
Property Items As List(Of String)
End Class

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

Decode JSON (String) - visual basic

How can I decode a JSON String in Visual Basic (without download programs)
Private Sub ViewHintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewHintToolStripMenuItem.Click
Dim instance As Net.WebClient = New Net.WebClient
Dim address As String = "https://pr2hub.com/files/artifact_hint.txt"
Dim returnValue As String
returnValue = instance.DownloadString(address)
Artifact.Text = returnValue
HintText.Show()
HintText.RichTextBox1.Text = returnValue
HintText.RichTextBox2.Text = returnValue
End Sub
By Decode I am assuming you mean Deserialize. Have you tried System.Web.Script.Serialization.JavaScriptSerializer ?
I don't understand what you're trying to deserialize above but here's a generic example:
Dim s as String = "{ 'name':'Fred', 'address':'123 Main', 'phone':'333-4444'}"
Dim jss As New JavaScriptSerializer
Dim o As Object = jss.Deserialize(Of Object)(s)
Note there is also a jss.Serialize method available.