Deserializando JSON en Visual Basic

Básicamente, estoy tratando de analizar los comentarios de un hilo de 4chan utilizando la API JSON de 4chan. https://github.com/4chan/4chan-API

básicamente, hay un cuadro de texto enriquecido llamado input, y otro llamado post_text_box. Lo que bash hacer es hacer que JSON de un hilo de 4chan ingrese en el cuadro de texto de entrada, y los comentarios se extraigan de ese JSON y se muestren en el cuadro de texto de salida

Sin embargo, cada vez que bash hacer clic en el botón Ir no sucede nada.

Aquí está mi código hasta ahora

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 rest As Integer Public Property bumplimit As Integer Public Property imagelimit As Integer Public Property replies As Integer Public Property images As Integer End Class 

Como está importando Newtonsoft.Json , puede usar el JsonConvert.DeserializeObject(String) :

 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 

Alternativamente, si no desea crear una clase para Post , puede usar JsonConvert.DeserializeAnonymousType(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 

EDITAR : Parece que estás obteniendo una matriz de la 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, "‌​rest" : 0, "bumplimit" : 0, "imagelimit" : 0, "replies" : 0, "images" : 0 } ] } 

En ese caso, deberá cambiar el tipo que se está deserializando a Post() :

Primero, agregue otra clase de envoltura pequeña:

 Public Class PostWrapper Public posts() As Post End Class 

Luego ajusta tu código de deserialización:

 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 

En lugar de necesitar definir una clase, puede deserializar el JSON en un Object , como este:

 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) 

Ahora, como ejemplo, puede recorrer el JSON deserializado y crear una tabla HTML, como esta:

 Dim sb As New StringBuilder() sb.Append("" & vbLf & "" & vbLf & "" & 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("" & vbLf, key) Next sb.Append("" & vbLf & "" & vbLf & "" & vbLf) For Each item As Dictionary(Of String, Object) In data("items") sb.Append("" & vbLf) For Each val As String In item.Values sb.AppendFormat(" " & vbLf, val) Next Next sb.Append("" & vbLf & "" & vbLf & "
{0}
{0}
") Dim myTable As String = sb.ToString()

Descargo de responsabilidad: Trabajo con C # a diario y este es un ejemplo de C # que usa una dynamic que se convirtió a VB.NET. Por favor, perdóneme si hay algún error de syntax con esto.

Además, si tienes cadena json compleja. Si hay subclases, matrices, etc. en la cadena json, puede usar de esta manera a continuación. Lo intenté y funcionó para mí. Espero que te sea útil.

Accedí a los valores root-> simpleforecast-> forecastday [] -> date-> hight-> celsius, fahrenheit, etc. en la cadena json.

 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 

Nota:

Primero tienes que instalar Newtonsoft.Json en la consola nuget. Luego incluya el siguiente código en la parte superior de su código.

  Imports Newtonsoft.Json 

Paso: 1 Crear clase con propiedades get & set.

 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 

Paso: 2 Crea cadena como un formato json y conver como un modelo de objeto json.

  Dim json As String = "{'rno':'09MCA08','name':'Kannadasan Karuppaiah','stdsec':'MCA'}" Dim stuObj As Student = JsonConvert.DeserializeObject(Of Student)(json) 

Paso: 3 Simplemente cruza por nombre de objeto.entidad de la siguiente manera.

 MsgBox(stuObj.rno) MsgBox(stuObj.name) MsgBox(stuObj.stdsec)