JSON deserialize in vb.net code behind - json

I am a java developer and I am working on .net first time. I have used JSON with YUI, but this is first time I am using JQUERY. I have converted Java script object to JSON string using JSON.stringify() and I am getting the same JSON string in code behind, but when I tried to deserialize to the .net object, I am getting the value for property which is Integer, but I not getting the value for String object.
// Client Side
$("#ButtonSave").click(function () {
//convert gridview to JSON
var jsonData = new Array();
$.map($("table[id*=Gridview1] tr"), function (item, index) {
if ($(item).find("input[type=text]").length > 0) {
jsonData[index] = new Object();
jsonData[index].charge = $(item).find("input[type=text][id*=txtCharge]").val();
jsonData[index].produce = $(item).find("input[type=text][id*=txtProduce]").val();
jsonData[index].weight = $(item).find("input[type=text][id*=txtWeight]").val();
jsonData[index].feet = $(item).find("input[type=text][id*=txtFeet]").val();
jsonData[index].orderNumber = $(item).find("input[type=text][id*=txtOrderNumber]").val();
jsonData[index].comments = $(item).find("input[type=text][id*=txtComments]").val();
}
});
var jsonStringData = JSON.stringify(jsonData);
var jqxhr = $.ajax({
url: "Correction.aspx",
type: "POST",
timeout: 10000,
data: "jsonData=" + jsonStringData
})
.error(function () {
alert('Error');
})
.success(function (data) {
alert('Success');
});
});
//Code Behind
If Request.Form("jsonData") IsNot Nothing Then
Dim cita As New TurnDetailVO
Dim ser As New JavaScriptSerializer()
Dim items As List(Of TurnDetailVO) = ser.Deserialize(Of List(Of TurnDetailVO))(Request.Form("jsonData"))
items.RemoveAt(0)
For Each cita In items
Console.WriteLine(cita.CHARGE_ID, cita.PROD_ID)
Next
End If
// Value Object
Imports Microsoft.VisualBasic
Imports System.Runtime.Serialization
Public Class TurnDetailVO
Private _CHARGE As String
Private _PROD As String
Private _WEIGHT As Integer
Private _FEET As Integer
Private _ORDER_NUMBER As String
Private _COMMENTS As String
Public Sub New()
_CHARGE = " "
_PROD = " "
_WEIGHT = 0
_FEET = 0
_ORDER_NUMBER = " "
_COMMENTS = " "
End Sub
Public Property CHARGE() As String
Get
Return _CHARGE
End Get
Set(ByVal value As String)
_CHARGE = value
End Set
End Property
Public Property PROD() As String
Get
Return _PROD
End Get
Set(ByVal value As String)
_PROD = value
End Set
End Property
Public Property WEIGHT() As Integer
Get
Return _WEIGHT
End Get
Set(ByVal value As Integer)
_WEIGHT = value
End Set
End Property
Public Property FEET() As Integer
Get
Return _FEET
End Get
Set(ByVal value As Integer)
_FEET = value
End Set
End Property
Public Property ORDER_NUMBER() As String
Get
Return _ORDER_NUMBER
End Get
Set(ByVal value As String)
_ORDER_NUMBER = value
End Set
End Property
Public Property COMMENTS() As String
Get
Return _COMMENTS
End Get
Set(ByVal value As String)
_COMMENTS = value
End Set
End Property
Public Function Clone() As TurnDetailVO
Return DirectCast(Me.MemberwiseClone(), TurnDetailVO)
End Function
End Class
// JSON String
"[null,
{"charge":"T860243","produce":"S877020","weight":"13188","feet":"2898","orderNumber":"AN46270","comments":""},
{"charge":"T860243","produce":"S877021","weight":"13538","feet":"2978","orderNumber":"AN46270","comments":""},
{"charge":"T860243","produce":"S877022","weight":"30118","feet":"6618","orderNumber":"AN46270","comments":""},
{"charge":"T860243","produce":"S877023","weight":"23455","feet":"3345","orderNumber":"AN46270","comments":""}]"

It looks like the deserializtion isn't behaving as expected due to two of your field names being different.
If I changed the property names PROD to PRODUCE and ORDER_NUMBER to ORDERNUMBER I could get it working. Note that you can leave the private field names as they are, it is just the property names that need to change.

Related

Newtonsoft JSON parsing into object

My VB is a bit rusty but I need to parse a JSON string. I did it already in C# where I didn't have an issue. This is an old project and I'm using VS2008 for it.
This is my class:
Public Class ResponseMeta
Private _type As String
<JsonProperty("type")> _
Public Property type() As String
Get
Return _type.ToString()
End Get
Set(ByVal value As String)
_type = value
End Set
End Property
Private _message As String
<JsonProperty("message")> _
Public Property message() As String
Get
Return _message
End Get
Set(ByVal value As String)
_message = value
End Set
End Property
Private _message_v1 As String
<JsonProperty("message-v1")> _
Public Property message_v1() As String
Get
Return _message_v1
End Get
Set(ByVal value As String)
_message_v1 = value
End Set
End Property
Private _message_v2 As String
<JsonProperty("message-v2")> _
Public Property message_v2() As String
Get
Return _message_v2
End Get
Set(ByVal value As String)
_message_v2 = value
End Set
End Property
Private _message_v3 As String
<JsonProperty("message-v3")> _
Public Property message_v3() As String
Get
Return _message_v3
End Get
Set(ByVal value As String)
_message_v3 = value
End Set
End Property
Private _message_v4 As String
<JsonProperty("message-v4")> _
Public Property message_v4() As String
Get
Return _message_v4
End Get
Set(ByVal value As String)
_message_v4 = value
End Set
End Property
End Class
The code to deserialize is:
Dim test As String
test = "{""response-meta"":{""type"":""S"",""message"":"""",""Total No Of Records"":"""",""message-v1"":""1"",""message-v2"":"""",""message-v3"":"""",""message-v4"":""""}}"
Dim testcl As ResponseMeta
testcl = JsonConvert.DeserializeObject(Of ResponseMeta)(test)
All properties of the object are set to Nothing and if I add watch, it says:
type = {"Object reference not set to an instance of an object."}
I have now spent countless hours on this and Google doesn't found a hint or a clue of what might be getting wrong here.
Any suggestions are very welcome.
The JSON does not match up to what you are trying to parse it to.
You are missing a root object.
Public Class RootObject
Private _root As ResponseMeta
<JsonProperty("response-meta")> _
Public Property ResponseMeta() As ResponseMeta
Get
Return _root
End Get
Set(ByVal value As ResponseMeta)
_root = value
End Set
End Property
End Class
So based on the JSON you would need to deserialize to root object first then get the meta data
Dim root As RootObject = JsonConvert.DeserializeObject(Of RootObject)(test)
Dim testcl As ResponseMeta = root.ResponseMeta

JSon Serialize complex object with datatable inside

I have this kind of object:
Public Class ClasseProva
Inherits RM_Base
Public Sub New()
Me.NomeTabella = "ClasseProva"
End Sub
Private m_AZI_ID As Integer
Public Property AZI_ID() As Integer
Get
Return m_AZI_ID
End Get
Set(ByVal value As Integer)
m_AZI_ID = value
End Set
End Property
Private m_dtPROGETTI As DataTable
Public Function ProgettiRO() As DataTable
Return m_dtPROGETTI
End Function
Public Sub ProgettiWO(value As DataTable)
m_dtPROGETTI = value
End Sub
End Class
So if in my object there is no datatable, I know how to serialize using Json and use serialized object as cookie. So in this way I have
public ClasseProva CookieClasseProva
{
get
{
try
{
string myObjectJson = Request.Cookies["CookieClasseProva"].Value;
return JsonConvert.DeserializeObject<ClasseProva>(myObjectJson);
}
catch { return null; }
}
set
{
string myObjectJson = JsonConvert.SerializeObject(value);
var cookie = new HttpCookie("CookieClasseProva", myObjectJson)
{
Expires = DateTime.Now.AddYears(1)
};
Response.Cookies.Add(cookie);
}
}
But after I added datatable, serialization function doesn't serialize datatable.
EDIT:
I don't know how attach a project. But now I'm copying Class of my BL project
Public Class Class1
Private m_intValue As Integer
Public Property MyIntValue() As Integer
Get
Return m_intValue
End Get
Set(ByVal value As Integer)
m_intValue = value
End Set
End Property
Private m_dtValue As DataTable
Public Property MyDatatable() As DataTable
Get
Return m_dtValue
End Get
Set(value As DataTable)
m_dtValue = value
End Set
End Property
End Class
and code section of a simple page
Imports Newtonsoft.Json
Imports DatatableSerializationBL
Public Class _Default
Inherits Page
Public Property CookieUtente() As Class1
Get
Try
Dim myObjectJson As String = Request.Cookies("CookieUtente").Value
Return JsonConvert.DeserializeObject(Of Class1)(myObjectJson)
Catch
Return Nothing
End Try
End Get
Set(value As Class1)
Dim myObjectJson As String = JsonConvert.SerializeObject(value)
Dim cookie = New HttpCookie("CookieUtente", myObjectJson)
Response.Cookies.Add(cookie)
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim c As New Class1
c.MyIntValue = 1
c.MyDatatable = New DataTable
c.MyDatatable.NewRow()
CookieUtente = c
Console.WriteLine(CookieUtente.MyDatatable.Rows.Count)
End Sub
End Class
So in the design page , I print rows.count value and it prints 0
ROWS : <%= CookieUtente.MyDatatable.Rows.Count%>

How does one get the values from the inner classes of deserialized JSON?

I am trying to get the lat and lng values from the Google Geocode API. I set up the classes using a vb translation of parse google maps geocode json response to object using Json.Net. I can access the status, and the top level result, but I cannot seem to access the children of result, even though the data shows up in debug mode when I hover over result and open up the plus signs.
How does one get the values from the inner classes of deserialized json?
Lines setting decLat and decLon say "geometry is not a member of Systems.Array"
Dim result = New System.Net.WebClient().DownloadString(Request.ToString)
Response = JsonConvert.DeserializeObject(Of GoogleGeoCodeResponse)(result)
If Response.status = "OK" Then
decLat = Response.results.geometry.location.lat
decLon = Response.results.geometry.location.lng
Public Class GoogleGeoCodeResponse
Public Property status() As String
Get
Return m_status
End Get
Set(value As String)
m_status = Value
End Set
End Property
Private m_status As String
Public Property results() As results()
Get
Return m_results
End Get
Set(value As results())
m_results = Value
End Set
End Property
Private m_results As results()
End Class
Public Class results
Public Property formatted_address() As String
Get
Return m_formatted_address
End Get
Set(value As String)
m_formatted_address = Value
End Set
End Property
Private m_formatted_address As String
Public Property geometry() As Geometry
Get
Return m_geometry
End Get
Set(value As Geometry)
m_geometry = Value
End Set
End Property
Private m_geometry As Geometry
Public Property types() As String()
Get
Return m_types
End Get
Set(value As String())
m_types = Value
End Set
End Property
Private m_types As String()
Public Property address_components() As address_component()
Get
Return m_address_components
End Get
Set(value As address_component())
m_address_components = Value
End Set
End Property
Private m_address_components As address_component()
End Class
Public Class geometry
Public Property location_type() As String
Get
Return m_location_type
End Get
Set(value As String)
m_location_type = Value
End Set
End Property
Private m_location_type As String
Public Property location() As location
Get
Return m_location
End Get
Set(value As location)
m_location = Value
End Set
End Property
Private m_location As location
End Class
Public Class location
Public Property lat() As Decimal
Get
Return m_lat
End Get
Set(value As Decimal)
m_lat = value
End Set
End Property
Private m_lat As String
Public Property lng() As Decimal
Get
Return m_lng
End Get
Set(value As Decimal)
m_lng = value
End Set
End Property
Private m_lng As String
End Class
Public Class address_component
Public Property long_name() As String
Get
Return m_long_name
End Get
Set(value As String)
m_long_name = Value
End Set
End Property
Private m_long_name As String
Public Property short_name() As String
Get
Return m_short_name
End Get
Set(value As String)
m_short_name = Value
End Set
End Property
Private m_short_name As String
Public Property types() As String()
Get
Return m_types
End Get
Set(value As String())
m_types = Value
End Set
End Property
Private m_types As String()
End Class

asmx won't return JSON

I've completely rewritten this old asmx service function but I still can't get it to return JSON. It returns XML, even if I use ajax() and set the datatype and contenttype to json. I'm trying to use this function with Jquery dataTables. And I know there are tons of questions like this but all of them I've found are C# and I was unable to adapt them.
up-to-date pastebin of full asmx file: http://pastebin.com/swXKqgd4
new code
<WebMethod()> _
<WebGet(ResponseFormat:=WebMessageFormat.Json)> _
Public Function rptPendingServerRequests() As Generic.List(Of request)
Dim _conn As SqlConnection = New SqlConnection(connectionString)
Dim _dr As SqlDataReader
Dim Sql As String = String.Empty
Sql += "<My query here>"
Try
Dim _cmd As SqlCommand = New SqlCommand(Sql, _conn)
_conn.Open()
_dr = _cmd.ExecuteReader(CommandBehavior.CloseConnection)
If _dr.HasRows Then
Dim s As request
Dim c As New Generic.List(Of request)
While _dr.Read
s = New request
With s
.requestID = _dr("request_id")
.status = _dr("status")
.requester = _dr("req_by_user_id")
.assignee = _dr("user_id")
.nextAction = _dr("description")
End With
c.Add(s)
End While
Return c
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
_conn.Close()
End Try
End Function
New class
<Serializable()> _
Public Class request
Private _requestID As Integer
Public Property requestID() As Integer
Get
Return _requestID
End Get
Set(ByVal value As Integer)
_requestID = value
End Set
End Property
Private _requester As String
Public Property requester() As String
Get
Return _requester
End Get
Set(ByVal value As String)
_requester = value
End Set
End Property
Private _requestDate As Date
Public Property requestDate() As Date
Get
Return _requestDate
End Get
Set(ByVal value As Date)
_requestDate = value
End Set
End Property
Private _status As Integer
Public Property status() As Integer
Get
Return _status
End Get
Set(ByVal value As Integer)
_status = value
End Set
End Property
Private _assignee As String
Public Property assignee() As String
Get
Return _assignee
End Get
Set(ByVal value As String)
_assignee = value
End Set
End Property
Private _nextAction As String
Public Property nextAction() As String
Get
Return _nextAction
End Get
Set(ByVal value As String)
_nextAction = value
End Set
End Property
End Class
Original Code
<WebMethod()> _
<WebGet(ResponseFormat:=WebMessageFormat.Json)> _
Public Function rptPendingServerRequestsOld() As DataSet
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
sql = ""
sql += "<MY query here>"
connection = New SqlConnection(connectionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
Return ds
Catch ex As Exception
End Try
End Function
Client
$('#report').dataTable({
"bProcessing": true,
"sAjaxSource": 'reportdata.asmx/rptPendingServerRequests'
});
Since you're calling this method from JS instead of
<WebGet(ResponseFormat:=WebMessageFormat.Json)>
use
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
attribute. Also don't forget to mark your WebService class with
<ScriptService()>
attribute.
Change this line.
Public Function rptPendingServerRequests() As Generic.List(Of request)
to
Public Function rptPendingServerRequests() As String.

save x,y spectrum data in table in ms-access

I want to create a table for LEDs. This table creates information such as name, center wavelength and the spectrum, which itself is data in the format intensity over wavelenth as 2 x n table data.
I am a beginner in access and have currently no clue how to insert this to a table.
I could of course create for each LED a table on its own, but there will be hundreds of these spectrum datas.
Such a complex data structure may be difficult to implement in a database table. An option I propose is to have a set of classes that represent the data. Then you can serialize and deserialize (read and write) the data to a file.
Sample Implementation
Module Module1
Sub Main()
Dim leds = New List(Of LED)()
Dim rnd = New Random()
'create a bunch of LEDs
For i = 1 To 10
Dim led = New LED("LED " & (i + 1).ToString(), rnd.Next(0, i * 100))
For x = 1 To 10
led.Spectrum.Add(New SpectrumInfo(rnd.Next(1, 10), rnd.Next(1000, 10000)))
Next
leds.Add(led)
Next
' write the led data to a file
Using sw As New IO.StreamWriter("LED Data.ledx")
Dim xs = New System.Xml.Serialization.XmlSerializer(leds.GetType())
xs.Serialize(sw, leds)
End Using
'read the led data from a file
Dim leds2 = New List(Of LED)()
Using sr = New System.IO.StreamReader("LED Data.ledx")
Dim xs = New System.Xml.Serialization.XmlSerializer(leds2.GetType())
leds2 = DirectCast(xs.Deserialize(sr), List(Of LED))
End Using
'confirm the two are the same
Console.WriteLine("LEDs and LEDS2 are " & If(leds.SequenceEqual(leds2), "the same", "different"))
' alternate saving using binary serializer
' works in cases where XmlSerializer doesn't
' produces smaller files too
'save the led data
Using fs = New System.IO.FileStream("LED Data.ledb", IO.FileMode.Create)
Dim bf = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(fs, leds)
End Using
'read the led data
Dim leds3 = New List(Of LED)()
Using fs = New System.IO.FileStream("LED Data.ledb", IO.FileMode.Open)
Dim bf = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
leds3 = DirectCast(bf.Deserialize(fs), List(Of LED))
End Using
'confirm equality
Console.WriteLine("LEDs and LEDS3 are " & If(leds.SequenceEqual(leds3), "the same", "different"))
Console.WriteLine("LEDs2 and LEDS3 are " & If(leds2.SequenceEqual(leds3), "the same", "different"))
Console.ReadLine()
End Sub
End Module
<Serializable()> _
Public Class LED
Dim _name As String
Dim _cWL As Double
Dim _spectrum As List(Of SpectrumInfo)
Public Sub New()
_name = String.Empty
_cWL = 0
_spectrum = New List(Of SpectrumInfo)()
End Sub
Public Sub New(name As String, cwl As Double, ParamArray spectrum() As SpectrumInfo)
_name = name
_cWL = cwl
_spectrum = New List(Of SpectrumInfo)(spectrum)
End Sub
Public Property Name As String
Get
Return _name
End Get
Set(value As String)
_name = value
End Set
End Property
Public Property CenterWavelength As Double
Get
Return _cWL
End Get
Set(value As Double)
_cWL = value
End Set
End Property
Public ReadOnly Property Spectrum As List(Of SpectrumInfo)
Get
Return _spectrum
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
If Not (TypeOf obj Is LED) Then Return False
Dim l2 = DirectCast(obj, LED)
Return l2._name = _name AndAlso l2._cWL = _cWL AndAlso l2._spectrum.SequenceEqual(_spectrum)
End Function
Public Overrides Function ToString() As String
Return String.Format("{0} [{1}]", _name, _cWL)
End Function
Public Overrides Function GetHashCode() As Integer
Dim result As Integer
For Each spec In _spectrum
result = result Xor spec.GetHashCode()
Next
Return result Xor (_name.GetHashCode() + _cWL.GetHashCode())
End Function
End Class
<Serializable()> _
Public Structure SpectrumInfo
Dim _intensity As Double
Dim _wavelength As Double
Public Sub New(intensity As Double, wavelength As Double)
_intensity = intensity
_wavelength = wavelength
End Sub
Public ReadOnly Property Intensity As Double
Get
Return _intensity
End Get
End Property
Public ReadOnly Property Wavelength As Double
Get
Return _wavelength
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
If TypeOf obj Is SpectrumInfo Then
Dim si = DirectCast(obj, SpectrumInfo)
Return si._wavelength = _wavelength AndAlso si._intensity = _intensity
Else
Return False
End If
End Function
Public Overrides Function ToString() As String
Return String.Format("Intensity: {0}, Wavelength: {1}", _intensity, _wavelength)
End Function
Public Overrides Function GetHashCode() As Integer
Return _intensity.GetHashCode() Xor _wavelength.GetHashCode()
End Function
End Structure
You might look at http://r937.com/relational.html
I think you want:
LED Table
ID
LEDName
CenterWavelength
And then a table for spectra
ID
LedId
Intensisty
WaveLength