Working with nested json file visual basic - json

i have a nested json file that i want to deserialize, i keep getting an error " Object reference not set to an instance of an object."
here is my json file
[
{
"Name": "Junius",
"LastName": "Lekgwara",
"CellNo": [
{
"CellC": "072685345",
"Voda": "0728589303"
}
]
},
{
"Name": "Phuti",
"LastName": "Gravel",
"CellNo": [
{
"CellC": "08377777777",
"Voda": "089888888888"
}
]
},
{
"Name": "Donald",
"LastName": "Gravel",
"CellNo": [
{
"CellC": "0791408989",
"Voda": "0117689009"
}
]
}
]
here is my Person class
Public Class Person
Private _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Private _LastName As String
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
Public Property cellno As CellNo
End Class
Public Class CellNo
Public Property CellC As String
Public Property Voda As String
End Class
PersonList class
Public Class PersonList
Private _ListPerson As List(Of Person)
Public Property ListPerson() As List(Of Person)
Get
Return _ListPerson
End Get
Set(ByVal value As List(Of Person))
_ListPerson = value
End Set
End Property
Sub New()
_ListPerson = New List(Of Person)
End Sub
End Class
reading json file, when this sub is called i get an error
Public Async Sub LoadFromFile()
Dim reader As String = Await GetFile()
Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(ObservableCollection(Of Person)))
Dim ms As MemoryStream = New MemoryStream(Encoding.UTF8.GetBytes(reader))
Dim listOf As ObservableCollection(Of Person) = New ObservableCollection(Of Person)
listOf = serializer.ReadObject(ms)
For Each item In listOf
list.ListPerson.Add(item)
Debug.WriteLine(item.Name + " " + item.LastName + " " + item.cellno.CellC + " " + item.cellno.Voda) 'Object reference not set to an instance of an object, on item.cellno.CellC and item.cellno.Voda
Next
End Sub
i want to be able to reference it like
Dim person As Person = New Person()
lblName.Text = person.Name
lblLastName.Text = person.LastName
lblCellCNo.Text= person.cellno.CellC
lblCellVodaNo.Text= person.cellno.Voda
how can i fix this?

The JSON shown is a bit different than the class structs you want to use. Person is a List or Array already in the JSON. CellNo is also an array even though it appears in that sample to only have one class object per person.
So, you can skip your PersonList entirely:
Public Class CellNo
Public Property CellC As String
Public Property Voda As String
End Class
Public Class Person
Public Property Name As String
Public Property LastName As String
Public Property CellNo As List(Of CellNo)
End Class
Deserialize to a List(Of Person):
Dim jstr = ... (wherever it comes from)
Dim jp As List(Of Person)
jp = JsonConvert.DeserializeObject(Of List(Of Person))(jstr)
This is now quite usable as is without further manipulations:
For Each P As Person In jp
Console.WriteLine("{0} Cell Voda:{1}", P.Name, P.CellNo(0).Voda)
Next
Junius Cell Voda: 0728589303
Phuti Cell Voda: 089888888888
Donald Cell Voda: 0117689009
Optionally, you can deserialize to an array of Person, and define Person.CellNo as an array also.
i'm not using newtonsoft
You get the same results using NET:
Imports System.Web.Script.Serialization
Dim jss As New JavaScriptSerializer
Dim jp As List(Of Person)
jp = jss.Deserialize(Of List(Of Person))(jstr)

See.. your problem is that
the item List is not well prepared for what you want.
item.cellno HAS CHILD !!!
and
item.cellno.CellC
item.cellno.Voda
must be iterated..
For Each item In listOf
list.ListPerson.Add(item)
'Debug.WriteLine(item.Name + " " + item.LastName + " " + _
'you know that you have just 2 items in : CellNo, and play with that.
For i= 0 to 1
Item.CellNo(i) ' do something with ..
End For
Next
also read this : vb.net datatable Serialize to json

Solved the problem by using CellNo as an array
`"CellNo":[
"072685345",
"0728589303"
]
For Each item In listOf
list.ListPerson.Add(item)
Debug.WriteLine(item.Name + " " + item.LastName)
For Each i In item.CellNo
Debug.WriteLine(i)
Next
Next
display
Junius Lekgwara
Cell No: 072685345
Cell No: 0728589303
Phuti Gravel
Cell No: 08377777777
Cell No: 089888888888
Donald Gravel
Cell No: 0791408989
Cell No: 0117689009

Related

Getting info from JSON in VB.NET using Json.NET

I need to process this JSON:
{
"companies": [
{
"companyId": "S86jhs89F",
"companyName": "LoremIpsum"
}
],
"response_metadata": {
"next_cursor": 659,
"next_link": "somedata"
} }
How can I get companyId, companyName, next_cursor and next_link using VB.NET?
Update...
I found this...
Dim json As String = "{ ... textJSON ... }"
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
For Each grupo As JProperty In data
grupo.CreateReader()
Select Case grupo.Name
Case "companies"
For Each item As JObject In grupo.Values
output += vbCrLf + " -- " + item("companyId").ToString
output += vbCrLf + " -- " + item("companyName").ToString
Next
Case "response_metadata"
Dim dato As JObject = grupo.Value
output += vbCrLf + " -- " + dato("next_cursor").ToString
End Select
Next
I don´t know if this is the optimal way, but it is working...
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. If you were to do this, then you would get something that looks like the following:
Public Class Rootobject
Public Property companies() As Company
Public Property response_metadata As Response_Metadata
End Class
Public Class Response_Metadata
Public Property next_cursor As Integer
Public Property next_link As String
End Class
Public Class Company
Public Property companyId As String
Public Property companyName As String
End Class
You can use decorators to make the property names conform to a more .NET style if you wanted:
Public Class Rootobject
<JsonProperty("companies")>
Public Property Companies As IEnumerable(Of Company)
<JsonProperty("response_metadata")>
Public Property ResponseMetadata As Response_Metadata
End Class
Public Class Response_Metadata
<JsonProperty("next_cursor")>
Public Property NextCursor As Integer
<JsonProperty("next_link")>
Public Property NextLink As String
End Class
Public Class Company
<JsonProperty("companyId")>
Public Property CompanyId As String
<JsonProperty("companyName")>
Public Property CompanyName As String
End Class
Now you would use JsonConvert.DeserializeObject to convert the JSON literal to your root object. After that, it's just a matter of getting the required properties:
Dim conversion = JsonConvert.DeserializeObject(Of Rootobject)(literal)
Dim companyId = conversion.Companies.First().CompanyId
Dim companyName = conversion.Companies.First().CompanyName
' etc.
Example: https://dotnetfiddle.net/GiGKwI

How to deserialize nested JSON arrays with Json.Net?

I want to deserialize the response of a HTTP-Request to Objects.
The Response looks like this:
[
"BeginOfEnumerable",
[
{
"StatusID": 12345,
"ItemID": 987654
}
],
"EndOfEnumerable"
]
I am using Newtonsoft.Json.
I tried to use Visual Studio's Edit > Paste special > Paste JSON as Classes to create the class model, but the result looks strange to me:
Public Class Rootobject
Public Property Property1() As Object
End Class
Also, this throws an Exception:
Dim myObject As Rootobject = JsonConvert.DeserializeObject(response.Content)
» Unexpected character encountered while parsing value: .Path ", line
0, position 0.
I want to get the StatusID and ItemID.
A JSON Validator I used says this JSON is valid.
The JSON structure is valid, per se, you may have some difficulty with the strings that don't follow the name:value pattern.
You could deserialize only the inner array of values, as a List(class), e.g.,
Imports System.Collections.Generic
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class EnumObject
Public Property StatusId As Long
Public Property ItemId As Long
End Class
'[...]
Dim jsonEnumsTokens = JArray.Parse(response.Content)
Dim enumsArray = jsonEnumsTokens.Children.Skip(1).First().ToObject(Of List(Of EnumObject))()
which returns the list of EnumObject that contain the values, if that's all you're interested in and you don't need to handle this JSON in any other way, or serialize it back in the same form.
If you want to get the JSON representation of the arrays only:
Dim justTheArraysJson = jsonEnumsTokens.Children.Skip(1).First().ToString()
In case you want to perform deserialization and serialization, maintaining the structure, you could use a custom JsonConverter that handles this case.
The EnumObjectsConverter creates an intermediate structure that contains both the single strings and the array of values, contained in the EnumObjectArray property.
This also allows to serialize back to the original structure, if needed.
Call it as:
Dim enumArray = EnumObjectsHandler.Deserialize(response.Content)
Dim serialized = EnumObjectsHandler.Serialize(enumArray)
The EnumObjectsHandler class that provides the static methods for the serialization:
Public Class EnumObjectsHandler
Private Shared settings As JsonSerializerSettings = New JsonSerializerSettings() With {
.Converters = {New EnumObjectsConverter()}
}
Public Shared Function Deserialize(json As String) As List(Of EnumObjectsRoot)
Return JsonConvert.DeserializeObject(Of List(Of EnumObjectsRoot))(json, settings)
End Function
Public Shared Function Serialize(data As List(Of EnumObjectsRoot)) As String
Return JsonConvert.SerializeObject(data, settings)
End Function
Public Class EnumObject
Public Property StatusId As Long
Public Property ItemId As Long
End Class
Public Structure EnumObjectsRoot
Public Property EnumObjectArray As List(Of EnumObject)
Public Property Operation As String
Public Shared Widening Operator CType(objectArray As List(Of EnumObject)) As EnumObjectsRoot
Return New EnumObjectsRoot With {.EnumObjectArray = objectArray}
End Operator
Public Shared Widening Operator CType(op As String) As EnumObjectsRoot
Return New EnumObjectsRoot With {.Operation = op}
End Operator
End Structure
Friend Class EnumObjectsConverter
Inherits JsonConverter
Public Overrides Function CanConvert(t As Type) As Boolean
Return t Is GetType(EnumObjectsRoot)
End Function
Public Overrides Function ReadJson(reader As JsonReader, t As Type, existingValue As Object, serializer As JsonSerializer) As Object
Select Case reader.TokenType
Case JsonToken.String
Dim stringValue = serializer.Deserialize(Of String)(reader)
Return New EnumObjectsRoot() With {
.Operation = stringValue
}
Case JsonToken.StartArray
Dim arrayValue = serializer.Deserialize(Of List(Of EnumObject))(reader)
Return New EnumObjectsRoot() With {
.EnumObjectArray = arrayValue
}
End Select
Throw New Exception("EnumObjectsRoot could not be deserialized")
End Function
Public Overrides Sub WriteJson(writer As JsonWriter, untypedValue As Object, serializer As JsonSerializer)
Dim value = CType(untypedValue, EnumObjectsRoot)
If value.Operation IsNot Nothing Then
serializer.Serialize(writer, value.Operation)
Return
End If
If value.EnumObjectArray IsNot Nothing Then
serializer.Serialize(writer, value.EnumObjectArray)
Return
End If
Throw New Exception("EnumObjectsRoot could not be serialized")
End Sub
End Class
End Class

How to deserialize JSON which can be an array or a single object

I'm fairly new to using JSON.net and having trouble with some json I'm getting which sometime comes in as an array and sometimes as single object. Here is an example of what I'm seeing with the json
One way it comes in ...
{
"Make": "Dodge",
"Model": "Charger",
"Lines": [
{
"line": "base",
"engine": "v6",
"color": "red"
},
{
"line": "R/T",
"engine": "v8",
"color": "black"
}
],
"Year": "2013"
}
Another way it could come in
{
"Make": "Dodge",
"Model": "Charger",
"Lines": {
"line": "base",
"engine": "v6",
"color": "red"
},
"Year": "2013"
}
Here is what I've been using for code which works on the first way and throws an exception in the second case. Been scouring the web for ways to implement this and am really stuck.
Public Class jsonCar
Public Property make As String
Public Property model As String
Public Property lines As List(Of jsonCarLines)
Public Property year As String
End Class
Public Class jsonCarLines
Public Property line As String
Public Property engine As String
Public Property color As String
End Class
Module Module1
Private Const json As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": [{""line"":""base"",""engine"": ""v6"",""color"":""red""},{""line"":""R/T"",""engine"":""v8"",""color"":""black""}],""Year"":""2013""}"
'Private Const json As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": {""line"":""R/T"",""engine"":""v8"",""color"":""black""},""Year"":""2013""}"
Sub Main()
Dim car As jsonCar = JsonConvert.DeserializeObject(Of jsonCar)(json)
Console.WriteLine("Make: " & car.make)
Console.WriteLine("Model: " & car.model)
Console.WriteLine("Year: " & car.year)
Console.WriteLine("Lines: ")
For Each ln As jsonCarLines In car.lines
Console.WriteLine(" Name: " & ln.line)
Console.WriteLine(" Engine: " & ln.engine)
Console.WriteLine(" Color: " & ln.color)
Console.WriteLine()
Next
Console.ReadLine()
End Sub
End Module
I'm guessing this will likely need a custom JsonConverter, but I'm a bit at a loss as to how to set that up.
Here is how to get the SingleOrArrayConverter solution in the linked duplicate question working for your use case.
First, here is the VB-translated converter code. Take this and save it to a class file somewhere in your project. You can then easily reuse it for any future cases like this.
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class SingleOrArrayConverter(Of T)
Inherits JsonConverter
Public Overrides Function CanConvert(objectType As Type) As Boolean
Return objectType = GetType(List(Of T))
End Function
Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
Dim token As JToken = JToken.Load(reader)
If (token.Type = JTokenType.Array) Then
Return token.ToObject(Of List(Of T))()
End If
Return New List(Of T) From {token.ToObject(Of T)()}
End Function
Public Overrides ReadOnly Property CanWrite As Boolean
Get
Return False
End Get
End Property
Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
Throw New NotImplementedException
End Sub
End Class
Now that you have this converter, any time you have a property that can be either a list or a single item, all you have to do is declare it as a list in your class and then annotate that list with a JsonConverter attribute such that it uses the SingleOrArrayConverter class. In your case, that would look like this:
Public Class jsonCar
Public Property make As String
Public Property model As String
<JsonConverter(GetType(SingleOrArrayConverter(Of jsonCarLines)))>
Public Property lines As List(Of jsonCarLines)
Public Property year As String
End Class
Then, just deserialize as you normally would, and it works as expected.
Dim car As jsonCar = JsonConvert.DeserializeObject(Of jsonCar)(json)
Here is a complete demonstration: https://dotnetfiddle.net/msYNeQ
You could achieve this to modify your jsonCar class like below
Public Class jsonCar
Public Property make As String
Public Property model As String
Public Property linesCollection As List(Of jsonCarLines) // Change name
Public Property lines As String // Change the type to string
Public Property year As String
End Class
And the code should be like below:
Dim car As jsonCar = JsonConvert.DeserializeObject(Of jsonCar)(json)
If (car.lines.StartsWith("[")) Then
car.linesCollection = JsonConvert.DeserializeObject(List(Of jsonCarLines))(car.lines)
Else
car.linesCollection = new List(Of jsonCarLines)
car.linesCollection.Add(JsonConvert.DeserializeObject(Of jsonCarLines)(car.lines))
EndIf
Thanks to both crowcoder & Kundan. I combined the two approaches and came up with something that works with both json inputs. Here is the final code.
Public Class jsonCar
Public Property make As String
Public Property model As String
Public Property linesArray As List(Of jsonCarLines)
Public Property year As String
End Class
Public Class jsonCarLines
Public Property line As String
Public Property engine As String
Public Property color As String
End Class
Module Module1
'Private Const json As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": [{""line"":""base"",""engine"": ""v6"",""color"":""red""},{""line"":""R/T"",""engine"":""v8"",""color"":""black""}],""Year"":""2013""}"
Private Const json As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": {""line"":""R/T"",""engine"":""v8"",""color"":""black""},""Year"":""2013""}"
Sub Main()
Dim obj As JObject = JsonConvert.DeserializeObject(json)
Dim ln As JToken = obj("Lines")
Dim car As jsonCar = JsonConvert.DeserializeObject(Of jsonCar)(json)
If (ln.GetType() Is GetType(Newtonsoft.Json.Linq.JArray)) Then
car.linesArray = JsonConvert.DeserializeObject(Of List(Of jsonCarLines))(JsonConvert.SerializeObject(ln))
End If
If (ln.GetType() Is GetType(Newtonsoft.Json.Linq.JObject)) Then
car.linesArray = New List(Of jsonCarLines)
car.linesArray.Add(JsonConvert.DeserializeObject(Of jsonCarLines)(JsonConvert.SerializeObject(ln)))
End If
Console.WriteLine("Make: " & car.make)
Console.WriteLine("Model: " & car.model)
Console.WriteLine("Year: " & car.year)
Console.WriteLine("Lines: ")
For Each line As jsonCarLines In car.linesArray
Console.WriteLine(" Name: " & line.line)
Console.WriteLine(" Engine: " & line.engine)
Console.WriteLine(" Color: " & line.color)
Console.WriteLine()
Next
Console.ReadLine()
End Sub
End Module
Big thanks for the quick replies. This solved something I'd been spending a lot time off-and-on trying to figure out.
You can generically deserialize to Object and then inspect what you have. You can check for a JArray or JObject and act accordingly. You don't even need to deserialize into a specific type, you can work with the Dynamic objects but that may not be the best idea.
Module Module1
Sub Main()
Dim jsonWithArray As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": [{""line"":""base"",""engine"": ""v6"",""color"":""red""},{""line"":""R/T"",""engine"":""v8"",""color"":""black""}],""Year"":""2013""}"
Dim jsonWithObject As String = "{""Make"":""Dodge"",""Model"":""Charger"",""Lines"": {""line"":""base"",""engine"": ""v6"",""color"":""red""},""Year"":""2013""}"
Dim witharray As Newtonsoft.Json.Linq.JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonWithArray)
Dim withstring As Newtonsoft.Json.Linq.JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonWithObject)
Dim jtokArray As Newtonsoft.Json.Linq.JToken = witharray("Lines")
Dim jtokStr As Newtonsoft.Json.Linq.JToken = withstring("Lines")
If (jtokArray.GetType() Is GetType(Newtonsoft.Json.Linq.JArray)) Then
Console.WriteLine("its an array")
End If
If (jtokStr.GetType() Is GetType(Newtonsoft.Json.Linq.JObject)) Then
Console.WriteLine("its an object")
End If
Console.ReadKey()
End Sub
End Module

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

Trouble parsing Json into .net Object

I've studied other questions like this and I'm not doing something right. My vb.net class is wrong or something. Should my class only try to represent from candidates on or what?
I need help with deserializing this json:
{
"spatialReference" : {
"wkid" : 2286
},
"candidates" : [
{
"address" : "100 MAIN ST",
"location" : {
"x" : 1144782.9490543604,
"y" : 81361.525678694248
},
"score" : 100,
"attributes" : {
}
},
{
"address" : "100 E MAIN ST",
"location" : {
"x" : 1120908.3257195801,
"y" : 169917.71846333146
},
"score" : 77,
"attributes" : {
}
}
]
}
I am using the following code to deserialize:
Public Shared Function Deserialise(Of T)(ByVal json As String) As T
Dim obj As T = Activator.CreateInstance(Of T)()
Using ms As MemoryStream = New MemoryStream(Encoding.Unicode.GetBytes(json))
Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(obj.GetType())
obj = serializer.ReadObject(ms)
Return obj
End Using
End Function
And my vb.net class looks like this:
<DataContract()> _
Public Class SearchResults
Private mCandidates() As candidate
<DataContract()> _
Public Class SpatialReference
Private mwkId As String
<DataMember()> _
Public Property wkid() As String
Get
Return mwkId
End Get
Set(ByVal value As String)
mwkId = value
End Set
End Property
End Class
<DataMember()> _
Public Property Candidates() As candidate()
Get
Return mCandidates
End Get
Set(ByVal value As candidate())
mCandidates = value
End Set
End Property
End Class
<DataContract()> _
Public Class candidate
Private mAddress As String
Private mLocation As Location
Private mScore As String
Private mAttr As String
<DataMember()> _
Public Property address() As String
Get
Return mAddress
End Get
Set(ByVal value As String)
mAddress = value
End Set
End Property
<DataMember()> _
Public Property location() As Location
Get
Return mLocation
End Get
Set(ByVal value As Location)
mLocation = value
End Set
End Property
<DataMember()> _
Public Property score() As String
Get
Return mScore
End Get
Set(ByVal value As String)
mScore = value
End Set
End Property
<DataMember()> _
Public Property attributes() As String
Get
Return mAttr
End Get
Set(ByVal value As String)
mAttr = value
End Set
End Property
End Class
I dont know .net but i can tell you it related to JAVA. You can relate this with .Net
When we need to serialize or deserialize our class objects to json or from json we need Gson,
In Java we generally import tha package Gson package create its object for example:-
Suppose i have a class User, whose object you wanna serialize. Now to do this
take the whole object covert it to JSON with some key name with the help of Gson
jsonObject.put("KEYFORTHISjsonObject", gson.toJson(userClassObject));
Now you have serialized it to JSON,
While deserializing it
just create ur User object. Get Json Object from Json file
JSONObject jsonObject = new JSONObject(jsonFile.toString())
userObject2 = gson.fromJson(jsonObject.toString(), User.class);
so now userObject2 has all the values that you serialized earlier.
if you are not familiar with JAVA then Read about Gson for .net
or you can read this link as well http://james.newtonking.com/projects/json-net.aspx