Trying to parse JSON: Current JsonReader item is not an object - json

I already know to parse JSON in Java, but when I try to do it in VB.NET I get this error:
Newtonsoft.Json.JsonReaderException: 'Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.'*
This is the code:
Dim requestUrl = "https://financialmodelingprep.com/api/v3/quote/TSLA?apikey={API_KEY}"
Dim jsonCode As String = New WebClient().DownloadString(requestUrl)
Dim json As JObject = JObject.Parse(jsonCode)
Dim price = json.SelectToken("price")
MsgBox(price)
End Sub
The message contained in the JSON is this:
[ {
"symbol" : "TSLA",
"name" : "Tesla, Inc.",
"price" : 431.38000000,
"changesPercentage" : 0.33000000,
"change" : 1.43000000,
"dayLow" : 427.76000000,
"dayHigh" : 452.50000000,
"yearHigh" : 502.49000000,
"yearLow" : 65.42000000,
"marketCap" : 408905547776.00000000,
"priceAvg50" : 423.72656000,
"priceAvg200" : 306.00583000,
"volume" : 28554811,
"avgVolume" : 63881259,
"exchange" : "NASDAQ",
"open" : 439.50000000,
"previousClose" : 429.95000000,
"eps" : 0.52300000,
"pe" : 824.81836000,
"earningsAnnouncement" : "2020-10-21T16:07:16.000+0000",
"sharesOutstanding" : 947901033,
"timestamp" : 1604951080
} ]
I would like to extract "price" and put it in a double.

Since you know what the incoming payload looks like, you should go ahead and create a class to represent the object:
Public Class Quote
Public Property symbol As String
Public Property name As String
Public Property price As Double
Public Property changesPercentage As Double
Public Property change As Double
Public Property dayLow As Double
Public Property dayHigh As Double
Public Property yearLow As Double
Public Property marketCap As Double
Public Property priceAvg50 As Double
Public Property priceAvg200 As Double
Public Property volume As Double
Public Property avgVolume As Double
Public Property exchange As String
Public Property open As Double
Public Property previousClose As Double
Public Property eps As Double
Public Property pe As Double
Public Property earningsAnnouncement As DateTimeOffset
Public Property sharesOutstanding As UInteger
Public Property timestamp As UInteger
End Class
From here you can use the DeserializeObject method to deserialize the array, get the first item in the collection, and then get the necessary properties:
Dim quotes = JsonConvert.DeserializeObject(Of List(Of Quote))(jsonCode)
Dim tesla = quotes?.SingleOrDefault()
If (tesla IsNot Nothing) Then
Console.WriteLine(tesla.price)
End If

Related

Read REST API JSON reply

I have been searching the web back an forth but couldn't find a hint to my issue.
I'm calling a REST API via RestSharp Client. I retrieve a response like this:
{
"meta": {
"query_time": 0.007360045,
"pagination": {
"offset": 1,
"limit": 100,
"total": 1
},
"powered_by": "device-api",
"trace_id": "a0d33897-5f6e-4799-bda9-c7a9b5368db7"
},
"resources": [
"1363bd6422274abe84826dabf20cb6cd"
],
"errors": []
}
I want to query the value of resources at the moment. This is the code I use:
Dim id_request = New RestRequest("/devices/queries/devices/v1?filter=" + filter, Method.GET)
id_request.AddHeader("Accept", "application/json")
id_request.AddHeader("Authorization", "bearer " + bearer)
Dim data_response = data_client.Execute(id_request)
Dim data_response_raw As String = data_response.Content
Dim raw_id As JObject = JObject.Parse(data_response_raw)
Dim id = raw_id.GetValue("resources").ToString
Unfortunately, I'm only getting ["1363bd6422274abe84826dabf20cb6cd"] as a reply instead of 1363bd6422274abe84826dabf20cb6cd
Can anyone point me into the right direction?
I have also tried to deserialize using JsonConvert.DeserializeObject() but I somehow fail.
I found this solution here but if I try to rebuild it fails as it doesn't recognize the Dictionary part
Dim tokenJson = JsonConvert.SerializeObject(tokenJsonString)
Dim jsonResult = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jsonString)
Dim firstItem = jsonResult.Item("data").Item(0)
EDIT:
When trying to deserialize the root as suggested but seems as if the 2nd response is nested JSON.
I have a reply like:
dr = {
"meta": {
"query_time": 0.004813129,
"powered_by": "device-api",
"trace_id": "5a355c86-37f7-416d-96c4-0c8796c940fc"
},
"resources": [
{
"device_id": "1363bd6422274abe84826dabf20cb6cd",
"policies": [
{
"policy_type": "prevention",
"policy_id": "1d34205a4e2c4d1991431c037c8e5734",
"applied": true,
"settings_hash": "7cb00a74",
"assigned_date": "2021-02-22T13:56:37.759459481Z",
"applied_date": "2021-02-22T13:57:19.962692301Z",
"rule_groups": []
}
],
"meta": {
"version": "352"
}
}
],
"errors": []
}
and I tried:
Dim restApiResponse = JsonConvert.DeserializeObject(Of RestApiResponseRoot)(dr)
' This is your array of strings
Dim resources = restApiResponse.Resources
Unfortunately I get
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path 'resources', line 8, position 3.'
The resources Property is an array. As usual, you need to specify which element of the array you want to consider. In this case, the first one, i.e., the element at index 0.
Dim jsonObject = JObject.Parse(data_response_raw)
Dim firstResource = jsonObject("resources")(0).ToString()
If you instead want the array content as a String array, not just the first element - assuming resources could contain more than one string (it's an array after all) - deserialize to String():
Dim jsonObject = JObject.Parse(data_response_raw)
Dim resources = JsonConvert.DeserializeObject(Of String())(jsonObject("resources").ToString())
In case you need the whole JSON response, I suggest to deserialize to a class Model that represents the JSON:
Public Class RestApiResponseRoot
Public Property Meta As Meta
Public Property Resources As List(Of String)
Public Property Errors As List(Of Object)
End Class
Public Class Meta
<JsonProperty("query_time")>
Public Property QueryTime As Double
Public Property Pagination As Pagination
<JsonProperty("powered_by")>
Public Property PoweredBy As String
<JsonProperty("trace_id")>
Public Property TraceId As Guid
End Class
Public Class Pagination
Public Property Offset As Long
Public Property Limit As Long
Public Property Total As Long
End Class
You can then deserialize the Model's Root object - the class named RestApiResponseRoot here - and access its Properties as usual:
Dim restApiResponse = JsonConvert.DeserializeObject(Of RestApiResponseRoot)(
data_response_raw
)
' This is your array of strings
Dim resources = restApiResponse.Resources
The other JSON response is slightly different, the Response Property contains an array of objects instead of string.
Some more properties and nested object are added. You just need to adjust the Model.
Public Class RestApiResponseRoot2
Public Property Meta As RootObjectMeta
Public Property Resources As List(Of Resource)
Public Property Errors As List(Of Object)
End Class
Public Class RootObjectMeta
<JsonProperty("query_time")>
Public Property QueryTime As Double
<JsonProperty("powered_by")>
Public Property PoweredBy As String
<JsonProperty("trace_id")>
Public Property TraceId As Guid
End Class
Public Class Resource
<JsonProperty("device_id")>
Public Property DeviceId As String
Public Property Policies As List(Of Policy)
Public Property Meta As ResourceMeta
End Class
Public Class ResourceMeta
Public Property Version As String
End Class
Public Class Policy
<JsonProperty("policy_type")>
Public Property PolicyType As String
<JsonProperty("policy_id")>
Public Property PolicyId As String
Public Property Applied As Boolean
<JsonProperty("settings_hash")>
Public Property SettingsHash As String
<JsonProperty("assigned_date")>
Public Property AssignedDate As DateTimeOffset
<JsonProperty("applied_date")>
Public Property AppliedDate As DateTimeOffset
<JsonProperty("rule_groups")>
Public Property RuleGroups As List(Of Object)
End Class
Dim restApiResponse2 = JsonConvert.DeserializeObject(Of RestApiResponseRoot2)(dr)
Dim resources As List(Of Resource) = restApiResponse2.Resources
' DeviceId of the first Resources object
Dim deviceId = resources(0).DeviceId
You can use some on-line resources to handle your JSON objects:
JSON Formatter & Validator
QuickType - JSON to .Net classes - C#, no VB.Net
JSON Utils - JSON to .Net classes - includes VB.Net. Somewhat less capable than QuickType.
Try trimming the resources value with " character in first and last of the output

How to deserialize a List(Of Object) from JSON?

I have a List(Of Object) that I am using in a property of type IEnumerable(Of Object). I can serialize it fine but cannot work out then how to deserialize it from JSON back to a List(Of Object). Any help would be really great please.
My ViewModel:
Public Class ViewModel
Inherits ViewModelBase
Public Class MapSettings
<Display(Name:="Map Name", Description:="Enter a optional name for the map.", GroupName:="Map Settings")>
Public Property MapName As String
<Display(Name:="Map Description", Description:="Enter a optional description for the map.", GroupName:="Map Settings")>
Public Property MapDescription As String
<Display(Name:="Map Comments", Description:="Enter optional comments for the map.", GroupName:="Map Settings")>
Public Property MapComments As String
<Display(Name:="Map Version", Description:="Enter a optional version for the map.", GroupName:="Map Settings")>
Public Property MapVersion As String
End Class
Public Class GeneralSettings
<Display(Name:="Route Colour", Description:="Sets the colour of the routes design line on the map.", GroupName:="General Settings")>
Public Property Foreground As Color
End Class
Private _myItems() As IEnumerable(Of Object)
Public Property MyItems() As IEnumerable(Of Object)
Get
If _myItems Is Nothing Then
Return New List(Of Object)() From {
New MapSettings,
New GeneralSettings With {.Foreground = Colors.Blue}
}
Else
Return _myItems
End If
End Get
Set(value As IEnumerable(Of Object))
_myItems = value
OnPropertyChanged()
End Set
End Property
End Class
My serialize code that I cannot complete:
Dim MyItems_New = JsonConvert.DeserializeObject(Of MyItems???)(MyJsonString)
JSON:
{
"MyItems": [
{
"MapName": null,
"MapDescription": null,
"MapComments": null,
"MapVersion": null
},
{
"Foreground": "#FF0000FF"
}
]
}
I just found that Newtonsoft has built-in support for type handling, which can be enabled by setting the JsonSerializerSettings.TypeNameHandling property and passing it to the serialization methods. As long as you control the input, this should let you both serialize and deserialize your list without a problem.
Serialize:
Dim myItems = JsonConvert.SerializeObject(myVM.MyItems, Formatting.None, New JsonSerializerSettings() With { .TypeNameHandling = TypeNameHandling.Auto })
Deserialize:
Dim myItems_New = JsonConvert.DeserializeObject(Of List(Of Object))(MyJsonString, New JsonSerializerSettings() With { .TypeNameHandling = TypeNameHandling.Auto })
In your question, MyJsonString appears to be a serialized version of your ViewModel class rather than just the list itself. If this is the case, change DeserializeObject(Of List(Of Object)) to DeserializeObject(Of ViewModel).
Resulting JSON:
[
{
"$type": "MapSettings, YourProjectNamespace",
"MapName": "New York",
"MapDescription": "Map over New York",
"MapComments": null,
"MapVersion": "v1"
},
{
"$type": "GeneralSettings, YourProjectNamespace",
"Foreground": "#FF0000"
}
]
Try it online (C#):
https://dotnetfiddle.net/0jCIGL
However, if these two classes are all you are planning to use this list for, then you'd be better off using something along the lines of Jimi's proposed solution, as then you're always working with strongly-typed objects.

Trying To Deserialize JSON Dictionairy Using Objects

As standard, I've created a web request and receive a response as JSON format. I'm trying to deserialize this JSON using JSON.NET (I don't think I need this though).
I've tried using the following code, however I'm not entirely sure on how to make the object actually contain some data. When I run this code, I get an error message displaying that my JObject "current" is "Nothing".
Imports System.Net
Imports System.IO
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
ServicePointManager.DefaultConnectionLimit = 9999
Dim uriString As String = "https://dev.tescolabs.com/grocery/products/?query=chicken&offset=0&limit=2"
Dim uri As New Uri(uriString)
Dim r As HttpWebRequest = HttpWebRequest.Create(uri)
r.Headers("Ocp-Apim-Subscription-Key") = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
r.Method = "GET"
r.Proxy = Nothing
Dim re As HttpWebResponse = r.GetResponse()
Dim read As New StreamReader(re.GetResponseStream())
Dim raw As String = read.ReadToEnd()
Dim a As JObject = JObject.Parse(raw)
Dim current As JObject = DirectCast(a("image"), JObject)
MessageBox.Show(current("image"))
End Sub
End Class
Public Class Totals
Public Property all As Integer
Public Property _new As Integer
Public Property offer As Integer
End Class
Public Class Result
Public Property image As String
Public Property superDepartment As String
Public Property tpnb As Integer
Public Property ContentsMeasureType As String
Public Property name As String
Public Property UnitOfSale As Integer
Public Property description() As String
Public Property AverageSellingUnitWeight As Single
Public Property UnitQuantity As String
Public Property id As Integer
Public Property ContentsQuantity As Single
Public Property department As String
Public Property price As Single
Public Property unitprice As Single
End Class
So, in textbox1, should be each product, including all of the information for each product. After extracting all of this information, I would ultimately like to add the information for each product in a datagridview, to present the information in a more clear manner. However, I can't get past this stage.
I have now tried the following code:
Dim results = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Result)(raw)
For Each image In results.image
TextBox1.Text = "Image URL:" + results.image
Next
JSON I receive as response:
{
"uk" : {
"ghs" : {
"products" : {
"input_query" : "chicken",
"output_query" : "chicken",
"filters" : { },
"queryPhase" : "primary",
"totals" : {
"all" : 1358,
"new" : 9,
"offer" : 478
},
"config" : "default",
"results" : [ {
"image" : "http://img.tesco.com/Groceries/pi/325/5057008546325/IDShot_90x90.jpg",
"superDepartment" : "Fresh Food",
"tpnb" : 81866107,
"ContentsMeasureType" : "G",
"name" : "Tesco British Chicken Breast Portions 650G",
"UnitOfSale" : 1,
"description" : [ "Fresh class A skinless chicken breast fillet portions."],
"AverageSellingUnitWeight" : 0.746,
"UnitQuantity" : "KG",
"id" : 294007923,
"ContentsQuantity" : 650,
"department" : "Fresh Meat & Poultry",
"price" : 3.8,
"unitprice" : 5.85
}, {
"image" : "http://img.tesco.com/Groceries/pi/531/5054775703531/IDShot_90x90.jpg",
"superDepartment" : "Fresh Food",
"tpnb" : 64083120,
"ContentsMeasureType" : "KG",
"name" : "Tesco British Large Whole Chicken 1.55-1.95Kg",
"UnitOfSale" : 1,
"AverageSellingUnitWeight" : 1.785,
"description" : [ "Fresh Class A whole chicken without giblets."],
"UnitQuantity" : "KG",
"id" : 292276232,
"ContentsQuantity" : 1.75,
"department" : "Fresh Meat & Poultry",
"price" : 3.5,
"unitprice" : 2.0
} ],
"suggestions" : [ ]
}
}
}
}
However I still don't receive the image URL in textbox1, and have no idea as to why. Any help would be greatly appreciated.
I've never used JSON.NET or NEWTONSOFT, I tend to only mess around with JSON a little, I usually just use the 'built in' method.
Your results are in an array which is what your first problem would probably have been. Then your For Each looks like it's getting on the right track but not sure results are being referenced correctly?
Anyway...
He's a working example that will hopefully help.
I just made a simple WinForm and added a button.
I added a reference to: System.Web.Extensions
Try code below: (let me know how you got on)
Imports System.Web.Script.Serialization
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This is just my JSON source I used for testing. (The JSON response you posted)
Dim raw As String = IO.File.ReadAllText("C:\MEDIA\json_test.json")
'This should now be the same as your: Dim raw As String = read.ReadToEnd()
'From here on, try this:
'Deserialise
Dim ser As JavaScriptSerializer = New JavaScriptSerializer()
Dim Tesco As JSON = New JSON
Tesco = ser.Deserialize(Of JSON)(raw)
'Loop through results and print each image URL
For Each r As Result In Tesco.uk.ghs.products.results
Console.WriteLine("Image URL:" & r.image)
Next
End Sub
End Class
Public Class Totals
Public Property all As Integer
Public Property [new] As Integer
Public Property offer As Integer
End Class
Public Class Result
Public Property image As String
Public Property superDepartment As String
Public Property tpnb As Integer
Public Property ContentsMeasureType As String
Public Property name As String
Public Property UnitOfSale As Integer
Public Property description As String()
Public Property AverageSellingUnitWeight As Double
Public Property UnitQuantity As String
Public Property id As Integer
Public Property ContentsQuantity As Double
Public Property department As String
Public Property price As Double
Public Property unitprice As Double
End Class
Public Class Products
Public Property input_query As String
Public Property output_query As String
Public Property queryPhase As String
Public Property totals As Totals
Public Property config As String
Public Property results As Result()
Public Property suggestions As Object()
End Class
Public Class Ghs
Public Property products As Products
End Class
Public Class Uk
Public Property ghs As Ghs
End Class
Public Class JSON
Public Property uk As Uk
End Class

Getting Values of a JSON Object in vb.net

EDITED:
I got stuck while getting value of a JSON object in vb.net. My JSON request posts data like given below:
function submitEmail() {
var ClientsPersonalInfo = {
FullName: $("#FullName").val(),
PhoneNumber: $("#PhoneNumber").val(),
EmailAddress: $("#EmailAddress").val(),
DOB: $("#DOB").val(),
Occupation: $("#Occupation").val(),
NINumber: $("#NINumber").val(),
FullAddress: $("#FullAddress").val()
}
var ClientsData = {};
ClientsData.ClientsPersonalInfo = ClientsPersonalInfo;
var d = '{"ClientsData":' + JSON.stringify(ClientsData) + '}'
$.ajax({
type: "POST",
url: "add-new-client.aspx/SubmitEmail",
data: d,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response)
},
failure: function (msg) {
alert(msg);
}
});
}
JSON Object Looks Like
{
"ClientsPersonalInfo": {
"FullName": "",
"PhoneNumber": "",
"EmailAddress": "",
"DOB": "",
"Occupation": "",
"NINumber": "",
"FullAddress": ""
}
}
The above request returns an object in vb.net
VB Code:
<WebMethod()> _
Public Shared Function SubmitEmail(ByVal ClientsPersonalInfo As Object) As String
// What to do next to get object "ClientsPersonalInfo"
// I want to access properties of the object like
//Dim name As String = ClientsPersonalInfo.FullName
Return "Successfully Converted."
End Function
No I want to get values of this object and needs to append in a table. Please guide me how to get values of the above object?
First make sure your Json is in valid format using jsonlint
Then generate class base on it using jsonutils
Public Class ClientsPersonalInfo
Public Property FullName As String
Public Property PhoneNumber As String
Public Property EmailAddress As String
Public Property DOB As String
Public Property Occupation As String
Public Property NINumber As String
Public Property FullAddress As String
End Class
Public Class ClientsVehicleInfo
Public Property DrivingLicense As String
Public Property VehicleMakeModel As String
Public Property VehicleColour As String
Public Property PolicyNumber As String
Public Property TypeOfCover As String
Public Property VehicleStoredIn As String
End Class
Public Class ClientsData
Public Property ClientsPersonalInfo As ClientsPersonalInfo
Public Property ClientsVehicleInfo As ClientsVehicleInfo
End Class
Public Class ClientData
Public Property ClientsData As ClientsData
End Class
Use Newtonsoft JSON to deserialize your Json into object(s) then you may simply access its properties value. (remember to add Json.net to your project using Manage NuGet Packages)
Imports Newtonsoft.Json
Dim obj = JsonConvert.DeserializeObject(Of Dictionary(Of String, ClientsData))(yourJsonString)
At least one problem is not using Option Strict On. The code at fault:
Shared Function SubmitEmail(ByVal ClientData As Object) As String
Dim obj = JsonConvert.DeserializeObject(Of NewClientData)(ClientData)
If you turn on Option Strict that will not compile because JsonConvert.DeserializeObject takes a string argument. I am not sure why the exception (image now removed) seems to come from VB rather than Newtonsoft, but that isnt helping.
Your deserialized object will also just disappear when it goes out of scope when the method ends.
Applicable to Edit #9
The error mentioning a Dictionary seems misleading and probably something internal relating to how the properties are collected (many times json can be deserialized to a Dictionary(Of String, String). Given the json posted (with data):
{
"ClientsData": {
"ClientsPersonalInfo": {
"FullName": "Ziggy Le Strange",
"PhoneNumber": "505050",
"EmailAddress": "ziggy#foobar.com",
"DOB": "",
"Occupation": "Freelancer",
"NINumber": "7",
"FullAddress": "123 Easy street"
}
}
}
There are actually 3 classes: ClientsPersonalInfo with the data, ClientsData which is a class containing that one and in previous edits also included a ClientsVehicleInfo class.
But there is yet another class represented by the enclosing {...}. The robots who can create the classes for you name it Example or RootObject. In this case, I would call it ClientContainer.
This works:
' the outermost {}
Public Class ClientContainer
Public Property ClientsData As ClientsData
End Class
Public Class ClientsPersonalInfo
Public Property FullName As String
Public Property PhoneNumber As String
Public Property EmailAddress As String
Public Property DOB As String
Public Property Occupation As String
Public Property NINumber As String
Public Property FullAddress As String
End Class
Public Class ClientsData
Public Property ClientsPersonalInfo As ClientsPersonalInfo
Public Property ClientsVehicleInfo As ClientsVehicleInfo
End Class
Public Class ClientsVehicleInfo
' whatever it is supposed to hold
End Class
To deserialize the data (you may have to adapt it for web use, Shared seems incorrect to me):
' pass in the json AS STRING
' returns JUST the ClientsPersonalInfo
Public Function GetClientData(jsonData As String) As ClientsPersonalInfo
' you must use the container class
Dim client = JsonConvert.DeserializeObject(Of ClientContainer)(jsonData )
' TEST:
Console.WriteLine(client.ClientsData.ClientsPersonalInfo.FullName)
Return client.ClientsData.ClientsPersonalInfo
End Function
ClientsData seems to be an unneeded layer. The container could hold both of the other objects directly. If this is meant to hold info for more than one client, you would have keys in place of "ClientsData": in the json (e.g. "ziggy":{}, "zacky":{}, "zoey":{}.
Output:
Ziggy Le Strange
Since, as per comment, that vehicle info is part of the deal, you can change it to return ClientsData which holds both the Personal and Vehicle info:
Public Function GetClientData(jsonData As String) As ClientsData
' you must use the container class
Dim client = JsonConvert.DeserializeObject(Of ClientContainer)(jsonData )
Return client.ClientsData
Turn on Option Strict
Dont box parameters or returns As Object, they loose some of their meaning.
Keep in mind that the outermost braces in json represent a container object
Also, storing a Date as string looks bad too.

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