JavaScriptSerializer - Invalid JSON Primitive - json

Hello I am creating Desktop App I try to get my table show in my datagrid with source from remote sql server using PHP.
my PHP code to connecting and get the table values
<?php
include "koneksi.php";
$noresi = htmlspecialchars($_POST['NO_RESI']);
if($noresi=="") {
$rs = mysqli_query("SELECT * FROM CekResi");
}else {
$rs = mysqli_query("SELECT * FROM CekResi WHERE NO_RESI='$noresi'");
}
$rows = array();
while($row = mysqli_fetch_object($rs)){
array_push($rows, $row);
}
echo json_encode($rows);
?>
then with desktop app button i did this for showing to my datagrid
Imports System.Web.Script.Serialization
Private Sub btnTAMPILKAN_Click(sender As Object, e As EventArgs) Handles btnTAMPILKAN.Click
Dim WF As New System.Collections.Specialized.NameValueCollection
Dim Server As New System.Uri("http://mywebsite.com/resiapp/resi_view.php") 'URL File PHP
Dim WC As New Net.WebClient
Me.Cursor = Cursors.WaitCursor
Try
WF.Clear()
WF.Add("noresi", txtNORESI.Text.Trim())
Dim RV() As Byte = WC.UploadValues(Server, "POST", WF)
Dim JsonText As String = System.Text.Encoding.ASCII.GetString(RV)
Dim JSS As New JavaScriptSerializer
Dim NomorResi = JSS.Deserialize(Of List(Of KolomResiClass))(JsonText)
Dim BS As New BindingSource
BS.DataSource = NomorResi
dgCEKRESI.AutoGenerateColumns = True
dgCEKRESI.DataSource = BS
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message, "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
trying to Deserialize my class here
Public Class KolomResiClass
Public Property tgl_pckp As String
Public Property noresi As String
Public Property nama_cust As String
Public Property kota_pckp As String
Public Property kota_tjn As String
Public Property koli As String
Public Property berat As String
Public Property status As String
Public Property tgl_trm As String
Public Property vendor As String
Public Property rincian_cst As String
Public Property marketing As String
Public Property cost As String
Public Property inv_cust As String
Public Property margin As String
End Class
and always got error Invalid JSON Primitive
The error come when I click the button btnTAMPILKAN
Please help I really want to know where is my mistakes.

Related

How to iterate through all keys of json node

I'm trying to scrap the key values from this website API and it seems the json format it's not an array.
I'm working with console .Net core 6.0 using System.Text.Json.Nodes
The code I'm using is :
Dim streamData As Stream = Nothing
Using http As HttpClient = New HttpClient
Dim url As String = "https://api.hotbit.io/api/v1/market.status24h"
Dim t As Task(Of Stream) = http.GetStreamAsync(url)
streamData = t.Result
End Using
Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
Dim jsonData As JsonNode = jsonResponse("result")
Dim c As String = String.Empty
For Each jsonCurrency As JsonNode In jsonData.AsObject
c += jsonCurrency("last").ToString + " "
Next
but I get the error:
Cannot convert type 'KeyValuePair(Of String, JsonNode)' in JsonNode
What Am I doing wrong?
Thanks
Create a class to represent your JSON, like this:
Public Class MarketStatus
Public Property IsChange As Boolean
Public Property period As Integer
Public Property open As String
Public Property last As String
Public Property high As String
Public Property low As String
Public Property volume As String
Public Property deal As String
Public Property close As String
Public Property base_volume As String
Public Property quote_volume As String
End Class
Public Class Payload
Public Property _error As Object
Public Property result As Result
Public Property id As Integer
End Class
Public Class Result
<JsonPropertyName("0xBTCBTC")>
Public Property _0xBTCBTC As MarketStatus
<JsonPropertyName("0xBTCETH")>
Public Property _0xBTCETH As MarketStatus
<JsonPropertyName("0xCASHUSDT")>
Public Property _0xCASHUSDT As MarketStatus
<JsonPropertyName("1INCH1D3LUSDT")>
Public Property _1INCH1D3LUSDT As MarketStatus
' etc...
End Class
Now you can deserialize the entire payload by using JsonSerializer.Deserialize or JsonSerializer.DeserializeAsync:
Dim payloadObject = Await JsonSerializer.DeserializeAsync(Of Payload)(streamData)
Update
Per our conversation in the comments of this answer, you want to get the last value of each MarketStatus without having to type each one manually. What you can do is:
Use reflection to get every property of the Result class
Loop over the collection
Use PropertyInfo.GetValue to get the value of the deserialized object
Here is an example using the same variable names as above:
For Each propertyInformation In GetType(Result).GetProperties()
Dim status = DirectCast(propertyInformation.GetValue(payloadObject.result), MarketStatus)
Console.WriteLine("{0}.last = {1}", propertyInformation.Name, status.last)
Next
Fiddle: https://dotnetfiddle.net/USaAgc
I solved using
Dim result As JsonObject = jsonResponse("result").AsObject
For Each kvp In result.AsEnumerable
c &= kvp.Value("last").ToString & ", "
Next

How do I create a new JSON object from another JSON object in VB.Net?

I'm using the following code in VB.Net to fetch a set of time and temperature data in JSON format that I will end up charting. I want to convert the JSON data but I only get far as creating the jObject. After that, I get lost. I'll admit, I'm a bit of a newbie!
Imports System.Collections.Generic
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Partial Class public_html_JSON
Inherits System.Web.UI.Page
Public jResults As JObject
Public rawresp As String
Public strStartTime As String = ""
Public strEndTime As String = ""
Public rangeMinutes As Long
Public debugText As String
Private Sub form1_Load(sender As Object, e As EventArgs) Handles form1.Load
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim cstZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")
Dim cstTime As DateTime = TimeZoneInfo.ConvertTimeFromUtc(DateAdd(DateInterval.Day, 0, DateAdd(DateInterval.Hour, 0, Now().ToUniversalTime)), cstZone)request =
Dim url As String = "https://[somesite]?method=queryList4Chart&device.id=17002&endTime=" + strEndTime + "&sensorNumber=-1&startTime=" + strStartTime
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
rawresp = reader.ReadToEnd()
response = Nothing
jResults = JObject.Parse(rawresp)
But before I send it to the client-side, I want to:
Create a new JSON string using an "x, y" format with timeArray as "x" and dataArray[0] as
"y".
Reduce the number of data points by only keeping times with minutes divisible by 5. (i.e. 5,10,15,etc...)
Here is the data I want to transform:
"dataArray":[
[
{
"value":13.4
},
{
"value":13.2
},
{
"value":13.2
},
{
"value":13.5
}
],
[
{
"value":2.8
},
{
"value":2.8
},
{
"value":2.9
},
{
"value":3.0
}
]
],
"sensorArray":[
"1.TP1(℃)",
"2.TP2(℃)"
],
"timeArray":[
"2019/11/10 14:00:41",
"2019/11/10 14:05:40",
"2019/11/10 14:07:40",
"2019/11/10 14:10:40"
]
}
And I need it in this format:
[
{
"x":2019/11/10 14:00:00,
"y":13.4
},
{
"x":2019/11/10 14:05:00,
"y":13.2
},
{
"x":2019/11/10 14:10:00,
"y":13.5
}
]
How would I go about doing that?
Thanks to Craig's suggestion, here's the final, working code!
Imports System.Collections.Generic
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Partial Class KFPTempsV2
Inherits System.Web.UI.Page
Public strStartTime As String = ""
Public strEndTime As String = ""
Public rangeMinutes As Long
Public debugText As String
Public JSONxy As ArrayList = New ArrayList 'List of JSON strings
Private Sub form1_Load(sender As Object, e As EventArgs) Handles form1.Load
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim cstZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")
Dim cstTime As DateTime = TimeZoneInfo.ConvertTimeFromUtc(DateAdd(DateInterval.Day, 0, DateAdd(DateInterval.Hour, 0, Now().ToUniversalTime)), cstZone)
Dim DeviceList As IEnumerable(Of TemperatureDevice) = GetTemperatureDevices()
Dim rawResp As String
Dim url As String = ""
Dim objXY As New List(Of List(Of XY))
rangeMinutes = 1440
strStartTime = DateAdd(DateInterval.Minute, -rangeMinutes, cstTime).ToString("MM/dd/yyyy\%20HH:mm:00")
strEndTime = cstTime.ToString("MM/dd/yyyy\%20HH:mm:ss")
'Get data from each device
For Each dv As TemperatureDevice In DeviceList
url = "https://www.[somesite].com/deviceDataAction.do?method=queryList4Chart&device.id=" & dv.ID & "&endTime=" + strEndTime + "&sensorNumber=-1&startTime=" + strStartTime
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
rawResp = reader.ReadToEnd()
response = Nothing
Dim XYList As List(Of XY) = ConvertToXY(JsonConvert.DeserializeObject(Of JSONData)(rawResp))
JSONxy.Add(JsonConvert.SerializeObject(XYList))
objXY.Add(XYList) 'Store XYList for later use
Next
'Populate Current/H/L temperatures
Current1.InnerHtml = objXY(0)(objXY(0).Count - 1).y
High1.InnerHtml = MaxValue(objXY(0)).ToString
Low1.InnerHtml = MinValue(objXY(0)).ToString
Current2.InnerHtml = objXY(1)(objXY(1).Count - 1).y
High2.InnerHtml = MaxValue(objXY(1)).ToString
Low2.InnerHtml = MinValue(objXY(1)).ToString
Current3.InnerHtml = objXY(2)(objXY(2).Count - 1).y
High3.InnerHtml = MaxValue(objXY(2)).ToString
Low3.InnerHtml = MinValue(objXY(2)).ToString
Current4.InnerHtml = objXY(3)(objXY(3).Count - 1).y
High4.InnerHtml = MaxValue(objXY(2)).ToString
Low4.InnerHtml = MinValue(objXY(3)).ToString
End Sub
Function ConvertToXY(obj As JSONData) As List(Of XY)
Dim NewObj As List(Of XY) = New List(Of XY)
For i As Int16 = 0 To obj.DataArray(1).Length - 1
Dim oDate As DateTime = Convert.ToDateTime(obj.TimeArray(i))
Dim oNewDate As DateTime = New DateTime(oDate.Year, oDate.Month, oDate.Day, oDate.Hour, oDate.Minute, 0).AddMinutes(Math.Round(oDate.Second / 60))
If oNewDate.Minute Mod 5 = 0 Then
Dim objXY As XY = New XY
objXY.x = oNewDate.ToString("yyyy/MM/dd HH:mm:ss")
objXY.y = obj.DataArray(1)(i).Value
NewObj.Add(objXY)
End If
Next
Return NewObj
End Function
Function MinValue(oList As List(Of XY)) As String
Dim sglMin As Single = 200
For Each row As XY In oList
Try
If CSng(row.y) < sglMin Then
sglMin = CSng(row.y)
End If
Catch ex As Exception
End Try
Next
Return sglMin.ToString("F1")
End Function
Function MaxValue(oList As List(Of XY)) As String
Dim sglMax As Single = -200
For Each row As XY In oList
Try
If CSng(row.y) > sglMax Then
sglMax = CSng(row.y)
End If
Catch ex As Exception
End Try
Next
Return sglMax.ToString("F1")
End Function
Public Class JSONData
Public Property DataArray As DataArray()()
Public Property SensorArray As String()
Public Property TimeArray As String()
End Class
Public Class DataArray
Public Property Value As String
End Class
Class XY 'Important that xy field names be lowercase
Property x As String
Property y As String
End Class
Public Class TemperatureDevice
Public Name As String
Public ID As String
Public DatasetNum As Int16
Public Sub New()
End Sub
Public Sub New(ByVal _name As String,
ByVal _id As String,
ByVal _datasetNum As Int16
)
Name = _name
ID = _id
DatasetNum = _datasetNum
End Sub
End Class
Private Function GetTemperatureDevices() As IEnumerable(Of TemperatureDevice)
'Dataset choices TP1=0 Or TP2=1
Return New List(Of TemperatureDevice) From
{
New TemperatureDevice("Pump House", "17002", 1),
New TemperatureDevice("Planer", "7199", 1),
New TemperatureDevice("Sawmill", "7123", 1),
New TemperatureDevice("Wellons", "13293", 1)
}
End Function
End Class

Writing and Reading JSON in VB.net using Newtonsoft

This is my first time using JSON and I'm stuck. I'm trying to send a test SMS via http://sms.roamtech.com/smsapi/. The format is:
Send message format(json).
{
"result":{
"account":"xxxx",
"user":"xxxx",
"password":"xxxxxxxx",
"requestType":"BULK",
"alphanumeric":"xxxxxxxx",
"data":{
"linkid":"xxxxxxx",
"msisdn":"xxxxxxxxxxx",
"networkid":"1",
"message":"xxxxxxxxxxxx",
"callback":"http//test"
}
}
}
So, this is what I've come up with after reviewing various posts on this and other sites:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.IO
Imports System.Net
Imports System.Text
Module modJSON
Public Class clsResult
Public account As String
Public user As String
Public password As String
Public requestType As String
Public alphanumeric As String
Public data As New clsData
End Class
Public Class clsData
Public linkid As String
Public msisdn As String
Public networkid As String
Public message As String
Public callback As String
End Class
Public Class clsPOST
Public result As New clsResult
End Class
Public Sub chkJSON()
Dim r As New clsResult
Dim d As New clsData
Dim x As New clsPOST
r.account = "8852"
r.user = "username"
r.password = "password"
r.requestType = "BULK"
r.alphanumeric = "SMSLEO"
d.linkid = "1001"
d.msisdn = "2547xxxxxxxx"
d.networkid = "1"
d.message = "Just a test"
d.callback = "http://infiniti-africa.com/json"
r.data = d
x.result = r
Dim uriRoam As New Uri("http://sms.roamtech.com/smsapi")
Dim strJSON = JsonConvert.SerializeObject(x, Formatting.Indented)
Dim bytJSON = Encoding.UTF8.GetBytes(strJSON)
Dim result_post = SendRequest(uriRoam, bytJSON, "application/json", "POST")
MsgBox(result_post)
End Sub
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
End Module
The string strJSONseems to contain the correct key:value combinations. However, the code doesn't send the test SMS and I don't get any response. 'SendRequest' returns an empty string.
Also, I'm not sure what to use for the "callback" url, which is where the delivery report is forwarded.
Note:
1. "linkid" is a unique message ID
2. "msidn" is the recipient phone number
Any help is appreciated.
I have also tried using the following class:
Public Class JsonPost
Private urlToPost As String = ""
Public Sub New(ByVal urlToPost As String)
Me.urlToPost = urlToPost
End Sub
Public Function postData(pstData As Byte()) As Boolean
Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Try
webClient.Headers("content-type") = "application/json"
resByte = webClient.UploadData(Me.urlToPost, "post", pstData)
resString = Encoding.Default.GetString(resByte)
Console.WriteLine(resString)
webClient.Dispose()
Return True
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return False
End Function
End Class
Then calling:
Dim strJSON = JsonConvert.SerializeObject(x)
Dim bytJSON = Encoding.UTF8.GetBytes(strJSON)
Dim jsonPost As New JsonPost("http://sms.roamtech.com/smsapi")
jsonPost.postData(bytJSON)
I'm still getting nothing. Been struggling with this for three days now. Any ideas anyone?
Turns out I've been stressing for four days over a trailing slash (/). The API URL is:
http://sms.roamtech.com/smsapi/
While I've been using:
http://sms.roamtech.com/smsapi
Lesson learnt.

WebService Asp.Net Json not serialize a List(Of Class)

after a lot of time searching here and in the web, i'm posting my problem and my code for yours teach me how i do this works.
The problem is that the Json not serialize listUsuarios, when i use JavaScriptSerializer the return is "{}" and when i use JsonConvert.SerializeObject the return is "False".
Sorry for my bad english.
Here is the code...
USUARIOS.VB
Imports Microsoft.VisualBasic
Public Class Usuarios
Private _Codigo As Long
Private _Nome As String
Private _Telefone As String
Public Property Codigo As Integer
Get
Return _Codigo
End Get
Set(ByVal value As Integer)
_Codigo = value
End Set
End Property
Public Property Nome() As String
Get
Return _Nome
End Get
Set(ByVal value As String)
_Nome = value
End Set
End Property
Public Property Telefone() As String
Get
Return _Telefone
End Get
Set(ByVal value As String)
_Telefone = value
End Set
End Property
End Class
Public Class ListUsuarios
Private listUsuarios As List(Of Usuarios)
Public Sub New()
listUsuarios = New List(Of Usuarios)
End Sub
Public Sub AddItem(ByVal usuario As Usuarios)
listUsuarios.Add(usuario)
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
Public Function Item(ByVal Index As Integer) As Usuarios
Return CType(listUsuarios.Item(Index), Usuarios)
End Function
Public Function Count() As Integer
Return listUsuarios.Count
End Function
End Class
ANDROID.VB
Imports Newtonsoft.Json
Imports System.Configuration
Imports System.Data
Imports System.Data.OleDb
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Android
Inherits System.Web.Services.WebService
Dim Dt As DataTable
Dim Da As New OleDbDataAdapter
Dim Cmd As New OleDbCommand
Dim cn As New OleDb.OleDbConnection
<WebMethod()> _
Public Function Android(query As String) As String
Dim listUsuario As ListUsuarios = carregaDadosAccess(query)
Return retornaDadosJSON(listUsuario)
End Function
Private Function getConexaoDB() As OleDbConnection
Try
cn.ConnectionString = ConfigurationManager.ConnectionStrings("MyLocalAccess").ConnectionString
cn.Open()
Return cn
Catch ex As Exception
Throw ex
End Try
End Function
Private Sub closeConexaoDB(ByVal cn As OleDbConnection)
Try
If cn.State = ConnectionState.Open Then
cn.Close()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Private Function carregaDadosAccess(selectCommmand As String) As ListUsuarios
Dim usuario As Usuarios = Nothing
Dim listUsuario As New ListUsuarios
Dim i As Long = 0
Try
cn = getConexaoDB()
Dim da As New OleDb.OleDbDataAdapter(selectCommmand, cn)
Dim dt As New DataTable
Dim arrImage() As Byte = Nothing
Dim myMS As New IO.MemoryStream
da.Fill(dt)
If dt.Rows.Count > 0 Then
Do
usuario = New Usuarios
usuario.Codigo = dt.Rows(i).Item("key-codigo")
usuario.Nome = dt.Rows(i).Item("dad-descri")
usuario.Telefone = dt.Rows(i).Item("dad-telefo")
listUsuario.AddItem(usuario)
i = i + 1
If i = dt.Rows.Count Then Exit Do
Loop
Else
listUsuario = Nothing
End If
Catch ex As Exception
Throw ex
Finally
closeConexaoDB(cn)
End Try
Return listUsuario
End Function
Private Function retornaDadosJSON(listUsuario As ListUsuarios) As String
'Json serializer do próprio .net
'Dim JsonSerializer As New JavaScriptSerializer
'Return JsonSerializer.Serialize(listUsuario)
'Json serializer James Newton-King
Dim JsonSerializer As String = ""
Return JsonSerializer = JsonConvert.SerializeObject(listUsuario)
End Function
End Class
The first problem is you are returning a value that compares an empty string with the serialized json string and since the json serialized string is not empty. This is where the result of "False" is coming from.
You can fix that problem by changing the method to:
Private Function retornaDadosJSON(listUsuario As ListUsuarios) As String
Return JsonConvert.SerializeObject(listUsuario)
End Function
You can prevent this type of issue in the future by adding the following directives to the top of each file:
Option Explicit On
Option Strict On
or by setting the corresponding values in the project's Compile property page (you can also set these to default values for new projects in Visual Studio's Tools > Options > Projects and Solutions > VB Default).
Option Strict On would have prevented that code from compiling. It would also show you that there is a data type difference between _Codigo and Codigo (one is Long the other is Integer).
The second problem is that ListUsuarios isn't defined well for what you are trying to do with it. It would be much better to inherit from List(Of Usuarios) than your current design.
Changing to the following class will both reduce the code and ensure the data is serialized correctly:
Public Class ListUsuarios
Inherits List(Of Usuarios)
Public Sub AddItem(ByVal usuario As Usuarios)
Me.Add(usuario)
End Sub
End Class

Deserializing JSON in Visual basic

Basically, I'm trying to parse the comments from a 4chan thread using the 4chan JSON API. https://github.com/4chan/4chan-API
basically, there is one rich text box called input, and another called post_text_box. What im trying to do is make it so that JSON from a 4chan thread entered in the input text box, and comments are extracted from that JSON and displayed in the output text box
however, whenever I try clicking the Go button nothing happens.
Here is my code so far
Imports System.Web.Script.Serialization
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub start_button_Click(sender As Object, e As EventArgs) Handles start_button.Click
Dim j As Object = New JavaScriptSerializer().Deserialize(Of Post)(input.Text)
post_text_box.Text = j.com
End Sub
End Class
Public Class Rootobject
Public Property posts() As Post
End Class
Public Class Post
Public Property no As Integer
Public Property now As String
Public Property name As String
Public Property com As String
Public Property filename As String
Public Property ext As String
Public Property w As Integer
Public Property h As Integer
Public Property tn_w As Integer
Public Property tn_h As Integer
Public Property tim As Long
Public Property time As Integer
Public Property md5 As String
Public Property fsize As Integer
Public Property resto As Integer
Public Property bumplimit As Integer
Public Property imagelimit As Integer
Public Property replies As Integer
Public Property images As Integer
End Class
Since you're importing Newtonsoft.Json, you can just use the JsonConvert.DeserializeObject<T>(String) method:
Dim exampleJson As String = "{ 'no':'123', 'name':'Some Name', 'com':'This is a comment'}"
Dim post As Post = JsonConvert.DeserializeObject(Of Post)(exampleJson)
Dim com As String = post.com
post_text_box.Text = com
Alternatively, if you don't want to create a class for Post, you can use JsonConvert.DeserializeAnonymousType<T>(String, T):
Dim exampleJson As String = "{ 'no':'123', 'name':'Some Name', 'com':'This is a comment'}"
Dim tempPost = New With {Key .com = ""}
Dim post = JsonConvert.DeserializeAnonymousType(exampleJson, tempPost)
Dim com As String = post.com
post_text_box.Text = com
EDIT: It looks like you're getting an array back from the API:
{
"posts" : [{
"no" : 38161812,
"now" : "11\/19\/13(Tue)15:18",
"name" : "Anonymous",
"com" : ‌​ "testing thread for JSON stuff",
"filename" : "a4c",
"ext" : ".png",
"w" : 386,
"h" : 378,
"tn_w" : 250,
"tn_h" : 244,
"tim" ‌​ : 1384892303386,
"time" : 1384892303,
"md5" : "tig\/aNmBqB+zOZY5upx1Fw==",
"fsize" : 6234,
"‌​resto" : 0,
"bumplimit" : 0,
"imagelimit" : 0,
"replies" : 0,
"images" : 0
}
]
}
In that case, you will need to change the type that is being deserialized to Post():
First, add another small wrapper class:
Public Class PostWrapper
Public posts() As Post
End Class
Then adjust your deserialization code:
Dim json As String = input_box.Text
Dim postWrapper = JsonConvert.DeserializeObject(Of PostWrapper)(json) ' Deserialize array of Post objects
Dim posts = postWrapper.posts
If posts.Length = 1 Then ' or whatever condition you prefer
post_text_box.Text = posts(0).com
End If
Instead of needing to define a class, you can deserialize the JSON into an Object, like this:
Dim json As String = "{""items"":[{""Name"":""John"",""Age"":""20"",""Gender"":""Male""},{""Name"":""Tom"",""Age"":""25"",""Gender"":""Male""},{""Name"":""Sally"",""Age"":""30"",""Gender"":""Female""}]}"
Dim jss = New JavaScriptSerializer()
Dim data = jss.Deserialize(Of Object)(json)
Now, as an example, you could loop through the deserialized JSON and build an HTML table, like this:
Dim sb As New StringBuilder()
sb.Append("<table>" & vbLf & "<thead>" & vbLf & "<tr>" & vbLf)
' Build the header based on the keys of the first data item.
For Each key As String In data("items")(0).Keys
sb.AppendFormat("<th>{0}</th>" & vbLf, key)
Next
sb.Append("</tr>" & vbLf & "</thead>" & vbLf & "<tbody>" & vbLf)
For Each item As Dictionary(Of String, Object) In data("items")
sb.Append("<tr>" & vbLf)
For Each val As String In item.Values
sb.AppendFormat(" <td>{0}</td>" & vbLf, val)
Next
Next
sb.Append("</tr>" & vbLf & "</tbody>" & vbLf & "</table>")
Dim myTable As String = sb.ToString()
Disclaimer: I work with C# on a daily basis and this is a C# example using dynamic that was converted to VB.NET, please forgive me if there are any syntax errors with this.
Note:
First you have to install Newtonsoft.Json on nuget console. Then include following code on top of your code.
Imports Newtonsoft.Json
Step:1 Create class with get & set properties.
Public Class Student
Public Property rno() As String
Get
Return m_rno
End Get
Set(value As String)
m_rno = value
End Set
End Property
Private m_rno As String
Public Property name() As String
Get
Return m_name
End Get
Set(value As String)
m_name = value
End Set
End Property
Private m_name As String
Public Property stdsec() As String
Get
Return m_StdSec
End Get
Set(value As String)
m_StdSec = value
End Set
End Property
Private m_stdsec As String
End Class
Step: 2 Create string as a json format and conver as a json object model.
Dim json As String = "{'rno':'09MCA08','name':'Kannadasan Karuppaiah','stdsec':'MCA'}"
Dim stuObj As Student = JsonConvert.DeserializeObject(Of Student)(json)
Step: 3 Just traverses by object.entity name as follows.
MsgBox(stuObj.rno)
MsgBox(stuObj.name)
MsgBox(stuObj.stdsec)
Also, if you have complex json string. If there is subclasses, arrays, etc. in the json string, you can use this way at below. I tried it and it worked for me. I hope it will useful for you.
I accessed root->simpleforecast->forecastday[]->date->hight->celsius,fahrenheit values etc. in the json string.
Dim tempforecast = New With {Key .forecast = New Object}
Dim sFile As String = SimpleTools.RWFile.ReadFile("c:\\testjson\\test.json")
Dim root = JsonConvert.DeserializeAnonymousType(sFile, tempforecast)
Dim tempsimpleforecast = New With {Key .simpleforecast = New Object}
Dim forecast = jsonConvert.DeserializeAnonymousType(root.forecast.ToString(), tempsimpleforecast)
Dim templstforecastday = New With {Key .forecastday = New Object}
Dim simpleforecast = JsonConvert.DeserializeAnonymousType(forecast.simpleforecast.ToString(), templstforecastday)
Dim lstforecastday = simpleforecast.forecastday
For Each jforecastday In lstforecastday
Dim tempDate = New With {Key .date = New Object, .high = New Object, .low = New Object}
Dim forecastday = JsonConvert.DeserializeAnonymousType(jforecastday.ToString(), tempDate)
Dim tempDateDetail = New With {Key .day = "", .month = "", .year = ""}
Dim fcDateDetail = JsonConvert.DeserializeAnonymousType(forecastday.date.ToString(), tempDateDetail)
Weather_Forcast.ForcastDate = fcDateDetail.day.ToString() + "/" + fcDateDetail.month.ToString() + "/" + fcDateDetail.year.ToString()
Dim temphighDetail = New With {Key .celsius = "", .fahrenheit = ""}
Dim highDetail = JsonConvert.DeserializeAnonymousType(forecastday.high.ToString(), temphighDetail)
Dim templowDetail = New With {Key .celsius = "", .fahrenheit = ""}
Dim lowDetail = JsonConvert.DeserializeAnonymousType(forecastday.low.ToString(), templowDetail)
Weather_Forcast.highCelsius = Decimal.Parse(highDetail.celsius.ToString())
Weather_Forcast.lowCelsius = Decimal.Parse(lowDetail.celsius.ToString())
Weather_Forcast.highFahrenheit = Decimal.Parse(lowDetail.fahrenheit.ToString())
Weather_Forcast.lowFahrenheit = Decimal.Parse(lowDetail.fahrenheit.ToString())
Weather_Forcast09_Result.Add(Weather_Forcast)
Next