-
Aug 12th, 2013, 02:17 PM
#1
Thread Starter
Addicted Member
JSON parsing
Hello all,
Im desperatly trying to read JSON array combinate format for 2 days without success, i'm using json.net(Newtonsoft.Json) library but i guess im doing something wrong...
JSON:
Code:
[{"name": "X-men 1", "links": null, "dest": 1, "pid": 18, "site": "", "linksdone": 9, "fids": null, "sizetotal": 9023234659, "sizedone": 9023234659, "linkstotal": 9, "folder": "X-men 1", "password": "", "order": 0}, {"name": "X-men 2", "links": null, "dest": 1, "pid": 19, "site": "", "linksdone": 13, "fids": null, "sizetotal": 12774010166, "sizedone": 12774010166, "linkstotal": 13, "folder": "X-men 2", "password": "", "order": 1}, {"name": "X-men Origins", "links": null, "dest": 1, "pid": 21, "site": "", "linksdone": 10, "fids": null, "sizetotal": 9810772035, "sizedone": 9810772035, "linkstotal": 10, "folder": "X-men Origins", "password": "", "order": 2}, {"name": "X-men 3 Last Stand", "links": null, "dest": 1, "pid": 22, "site": "", "linksdone": 13, "fids": null, "sizetotal": 12376276378, "sizedone": 12376276378, "linkstotal": 13, "folder": "X-men 3 Last Stand", "password": "", "order": 3}]
My Code:
Code:
Dim ret as srting = jSON data
Dim account As getQueue = JsonConvert.DeserializeObject(Of getQueue)(ret)
ERROR getting :
Code:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'pyLoad_GUI.getQueue' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
Please can anyone help me out ?? Or might use some other method ??
Thank you
-
Aug 12th, 2013, 02:59 PM
#2
Frenzied Member
Re: JSON parsing
Looks like you have an array or list of getQueue objects (represented in the JSON).
VB Code:
Dim account as List(of getQueue) = JsonConvert.DeserializeObject(Of getQueue)(ret) ' maybe?
'or
Dim account as getQueue() = JsonConvert.DeserializeObject(Of getQueue)(ret)
-
Aug 12th, 2013, 03:16 PM
#3
Re: JSON parsing
Well it all rather depends on what 'getQueue' is does it not? This ....
vb.net Code:
Dim account As DataTable = JsonConvert.DeserializeObject(Of DataTable)(ret)
DataGridView1.DataSource = account
... works perfectly.
As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"
Reviews: "dunfiddlin likes his DataTables" - jmcilhinney
Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!
-
Aug 12th, 2013, 04:13 PM
#4
Thread Starter
Addicted Member
Re: JSON parsing
Originally Posted by dunfiddlin
Well it all rather depends on what 'getQueue' is does it not? This ....
vb.net Code:
Dim account As DataTable = JsonConvert.DeserializeObject(Of DataTable)(ret) DataGridView1.DataSource = account
... works perfectly.
Well your solution works only on this case but with others does not
this is what containts getQuote:
Code:
Public Class getQueue
Private m_Name As String
Private m_Dest As String
Private m_Links As String
'Private m_CreatedDate As DateTime
'Private m_Roles As IList(Of String)
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
Public Property Dest() As String
Get
Return m_Dest
End Get
Set(value As String)
m_Dest = value
End Set
End Property
Public Property Links() As String
Get
Return m_Links
End Get
Set(value As String)
m_Links = value
End Set
End Property
End Class
-
Aug 12th, 2013, 04:15 PM
#5
Thread Starter
Addicted Member
Re: JSON parsing
for example this does not work with DataGrid
Code:
https://dl.dropboxusercontent.com/u/38234344/JSONExample.txt
Can you please try it as well ??
-
Aug 12th, 2013, 04:26 PM
#6
Re: JSON parsing
Running that JSON through a class parsing system, I actually get three classes put together...but that doesn't mean it's right.
Code:
Public Class Rootobject
Public Property Property1() As Class1()
Get
Return m_Property1
End Get
Set
m_Property1 = Value
End Set
End Property
Private m_Property1 As Class1()
End Class
Public Class Class1
Public Property name() As String
Get
Return m_name
End Get
Set
m_name = Value
End Set
End Property
Private m_name As String
Public Property links() As Link()
Get
Return m_links
End Get
Set
m_links = Value
End Set
End Property
Private m_links As Link()
Public Property dest() As Integer
Get
Return m_dest
End Get
Set
m_dest = Value
End Set
End Property
Private m_dest As Integer
Public Property pid() As Integer
Get
Return m_pid
End Get
Set
m_pid = Value
End Set
End Property
Private m_pid As Integer
Public Property site() As String
Get
Return m_site
End Get
Set
m_site = Value
End Set
End Property
Private m_site As String
Public Property linksdone() As Integer
Get
Return m_linksdone
End Get
Set
m_linksdone = Value
End Set
End Property
Private m_linksdone As Integer
Public Property fids() As Object
Get
Return m_fids
End Get
Set
m_fids = Value
End Set
End Property
Private m_fids As Object
Public Property sizetotal() As Long
Get
Return m_sizetotal
End Get
Set
m_sizetotal = Value
End Set
End Property
Private m_sizetotal As Long
Public Property sizedone() As Long
Get
Return m_sizedone
End Get
Set
m_sizedone = Value
End Set
End Property
Private m_sizedone As Long
Public Property linkstotal() As Object
Get
Return m_linkstotal
End Get
Set
m_linkstotal = Value
End Set
End Property
Private m_linkstotal As Object
Public Property folder() As String
Get
Return m_folder
End Get
Set
m_folder = Value
End Set
End Property
Private m_folder As String
Public Property password() As String
Get
Return m_password
End Get
Set
m_password = Value
End Set
End Property
Private m_password As String
Public Property order() As Integer
Get
Return m_order
End Get
Set
m_order = Value
End Set
End Property
Private m_order As Integer
End Class
Public Class Link
Public Property status() As Integer
Get
Return m_status
End Get
Set
m_status = Value
End Set
End Property
Private m_status As Integer
Public Property format_size() As String
Get
Return m_format_size
End Get
Set
m_format_size = Value
End Set
End Property
Private m_format_size As String
Public Property name() As String
Get
Return m_name
End Get
Set
m_name = Value
End Set
End Property
Private m_name As String
Public Property plugin() As String
Get
Return m_plugin
End Get
Set
m_plugin = Value
End Set
End Property
Private m_plugin As String
Public Property url() As String
Get
Return m_url
End Get
Set
m_url = Value
End Set
End Property
Private m_url As String
Public Property packageID() As Integer
Get
Return m_packageID
End Get
Set
m_packageID = Value
End Set
End Property
Private m_packageID As Integer
Public Property fid() As Integer
Get
Return m_fid
End Get
Set
m_fid = Value
End Set
End Property
Private m_fid As Integer
Public Property [error]() As String
Get
Return m_error
End Get
Set
m_error = Value
End Set
End Property
Private m_error As String
Public Property statusmsg() As String
Get
Return m_statusmsg
End Get
Set
m_statusmsg = Value
End Set
End Property
Private m_statusmsg As String
Public Property order() As Integer
Get
Return m_order
End Get
Set
m_order = Value
End Set
End Property
Private m_order As Integer
Public Property size() As Integer
Get
Return m_size
End Get
Set
m_size = Value
End Set
End Property
Private m_size As Integer
End Class
Just a bit of starting ground, perhaps.
-
Aug 12th, 2013, 04:36 PM
#7
Thread Starter
Addicted Member
Re: JSON parsing
Nope nothing chanage, still same error im getting damn im so frustrated
-
Aug 12th, 2013, 07:41 PM
#8
Re: JSON parsing
Well your solution works only on this case but with others does not
I wasn't suggesting DataTable as a universal receiver, I was just illustrating that the success or otherwise of the procedure relies on getting the correct object type to deserialize to. With the class code in front of me, there is a rather obvious flaw, in that you apparently intend to declare the properties as arrays (correct although not perhaps the best way to handle it) but you set the properties from a single value variable (very much not correct!) The JSon returns a multi value object but you are deserializing it to a single value Class which is exactly what the error was complaining about.
If I get time tomorrow I'll play around a bit more with the second JSon example you've provided. If as formlesstree4 suggests it's actually 3 classes then it obviously wouldn't be appropriate for DataTable. I'll also have a deeper look into json.net which is new to me to see if there might be a better way of going about this.
If I get
As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"
Reviews: "dunfiddlin likes his DataTables" - jmcilhinney
Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!
-
Aug 13th, 2013, 02:30 AM
#9
Thread Starter
Addicted Member
Re: JSON parsing
Originally Posted by dunfiddlin
I wasn't suggesting DataTable as a universal receiver, I was just illustrating that the success or otherwise of the procedure relies on getting the correct object type to deserialize to. With the class code in front of me, there is a rather obvious flaw, in that you apparently intend to declare the properties as arrays (correct although not perhaps the best way to handle it) but you set the properties from a single value variable (very much not correct!) The JSon returns a multi value object but you are deserializing it to a single value Class which is exactly what the error was complaining about.
If I get time tomorrow I'll play around a bit more with the second JSon example you've provided. If as formlesstree4 suggests it's actually 3 classes then it obviously wouldn't be appropriate for DataTable. I'll also have a deeper look into json.net which is new to me to see if there might be a better way of going about this.
If I get
Thank you so much please keep me updateted
-
Aug 13th, 2013, 11:55 AM
#10
Re: JSON parsing
Originally Posted by dunfiddlin
If as formlesstree4 suggests it's actually 3 classes then it obviously wouldn't be appropriate for DataTable. I'll also have a deeper look into json.net which is new to me to see if there might be a better way of going about this. If I get
Hey, that's what Visual Studio tells me
-
Aug 14th, 2013, 12:30 AM
#11
Thread Starter
Addicted Member
-
Aug 14th, 2013, 05:15 AM
#12
Re: JSON parsing
http://jsonlint.com/ says that JSON is valid
Here is an example of a web method I have - works with JSON
Code:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False)> _
Public Function SavePanelService(ByVal toddtype As String, ByVal fromddtype As String, ByVal fromwho As String _
, ByVal source As IList(Of Dictionary(Of String, String)), ByVal objReturn As Dictionary(Of String, String) _
, ByVal username As String) As String
The parameter
ByVal source As IList(Of Dictionary(Of String, String))
is what is needed for a JSON ARRAY-of-OBJECTS, which is what you have.
-
Aug 14th, 2013, 05:18 AM
#13
Thread Starter
Addicted Member
Re: JSON parsing
Originally Posted by szlamany
http://jsonlint.com/ says that JSON is valid
Here is an example of a web method I have - works with JSON
Code:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False)> _
Public Function SavePanelService(ByVal toddtype As String, ByVal fromddtype As String, ByVal fromwho As String _
, ByVal source As IList(Of Dictionary(Of String, String)), ByVal objReturn As Dictionary(Of String, String) _
, ByVal username As String) As String
The parameter
ByVal source As IList(Of Dictionary(Of String, String))
is what is needed for a JSON ARRAY-of-OBJECTS, which is what you have.
Thank you for help but i have no idea what you mean
-
Aug 14th, 2013, 05:21 AM
#14
Re: JSON parsing
Does this work?
Code:
Dim test as IList(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(IList(Of Dictionary(Of String, String)))(ret)
-
Aug 14th, 2013, 05:27 AM
#15
Thread Starter
Addicted Member
Re: JSON parsing
Originally Posted by szlamany
Does this work?
Code:
Dim test as IList(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(IList(Of Dictionary(Of String, String)))(ret)
well cannot try coz of this "Error 1 'IList' is a type and cannot be used as an expression. dddd 25
"
-
Aug 14th, 2013, 05:28 AM
#16
Re: JSON parsing
Add this and see if it works...
Imports System.Collections.Generic
Otherwise see if changing ILIST to LIST works...
-
Aug 14th, 2013, 05:35 AM
#17
Re: JSON parsing
Or do you need to use
Code:
Dim test as IList(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(Of IList(Of Dictionary(Of String, String)))(ret)
or
Code:
Dim test as IList(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(ret)
or
Code:
Dim test as New IList(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(Of IList(Of Dictionary(Of String, String)))(ret)
or
Code:
Dim test as New IList(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(ret)
-
Aug 14th, 2013, 05:44 AM
#18
Re: JSON parsing
If any of those work then I am guessing that changing this
IList(Of Dictionary(Of String, String))
to
IList(Of getQueue)
might fill your class...
-
Aug 14th, 2013, 06:22 AM
#19
Thread Starter
Addicted Member
Re: JSON parsing
Damn nothing works at all :
THis would make sense to me :
Code:
Dim test As IList(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(Of IList(Of Dictionary(Of String, String)))(ret)
However it does not and getting this error :
Code:
Object type System.Collections.Generic.List`1[pyLoad_GUI.Link] cannot retype to System.Collections.Generic.IList`1[System.Collections.Generic.Dictionary`2[System.String,System.String]].
-
Aug 14th, 2013, 06:23 AM
#20
Re: JSON parsing
That says they use LIST internally - so ILIST won't work.
Change it to LIST(of...)
-
Aug 14th, 2013, 06:27 AM
#21
Thread Starter
Addicted Member
Re: JSON parsing
Hmm change it to string this is result, not even know what is that meant
Code:
Error reading string. Unexpected token: StartArray. Path '[0].links', line 1, position 31.
-
Aug 14th, 2013, 06:28 AM
#22
Re: JSON parsing
Did you see my post #20??
-
Aug 14th, 2013, 06:32 AM
#23
Thread Starter
Addicted Member
Re: JSON parsing
I did no matter i use Ilist or List still the same error
Code:
Error reading string. Unexpected token: StartArray. Path '[0].links', line 1, position 31.
-
Aug 14th, 2013, 06:43 AM
#24
Re: JSON parsing
How about
List(Of getQueue)
Since that's ultimately where you want it to go...
-
Aug 14th, 2013, 07:03 AM
#25
Re: JSON parsing
I think MonkOFox was quite close:
Originally Posted by MonkOFox
VB Code:
Dim account as List(of getQueue) = JsonConvert.DeserializeObject(Of getQueue)(ret) ' maybe?
'or
Dim account as getQueue() = JsonConvert.DeserializeObject(Of getQueue)(ret)
Should be
Code:
Dim account As List(Of getQueue) = JsonConvert.DeserializeObject(Of List(Of getQueue))(ret)
'or
Dim account As getQueue() = JsonConvert.DeserializeObject(Of getQueue())(ret)
Can be used with formlesstree4's code, but be aware that there are only two classes: you can ignore Class Rootobject
Code:
Dim ret As String ' = JSON string
Dim account As List(Of Class1) = JsonConvert.DeserializeObject(Of List(Of Class1))(ret)
-
Aug 14th, 2013, 08:41 AM
#26
Thread Starter
Addicted Member
Re: JSON parsing
Originally Posted by Inferrd
I think MonkOFox was quite close:
Should be
Code:
Dim account As List(Of getQueue) = JsonConvert.DeserializeObject(Of List(Of getQueue))(ret)
'or
Dim account As getQueue() = JsonConvert.DeserializeObject(Of getQueue())(ret)
Can be used with formlesstree4's code, but be aware that there are only two classes: you can ignore Class Rootobject
Code:
Dim ret As String ' = JSON string
Dim account As List(Of Class1) = JsonConvert.DeserializeObject(Of List(Of Class1))(ret)
Man thank you million this works pretty well
-
Aug 14th, 2013, 08:41 AM
#27
Re: JSON parsing
Originally Posted by szlamany
How about
List(Of getQueue)
Since that's ultimately where you want it to go...
And how is that different then what is posted here?
-
Aug 14th, 2013, 08:45 AM
#28
Thread Starter
Addicted Member
Re: JSON parsing
Originally Posted by szlamany
And how is that different then what is posted here?
You have been right as well, i' just an idiot Sorry mate
-
Aug 14th, 2013, 08:46 AM
#29
Re: JSON parsing
Just a thought, as I see it dunfiddlin had the right idea unless I am missing something.
Take (yep I did not write out all columns)
Code:
Public Class getQueue
Public Property Name() As String
Public Property Dest() As String
Public Property Links() As String
Public Sub New()
End Sub
Public Overrides Function ToString() As String
Return "'" & MyClass.Name & "' '" & Dest & "' '" &
IIf(String.IsNullOrWhiteSpace(Links), "(empty)", Links).ToString & "'"
End Function
End Class
and convert to DataTable
Code:
Dim dt As DataTable = Newtonsoft.Json.JsonConvert.DeserializeObject(Of DataTable)(MyJsonString)
Knowing in simple terms we delt with a collection (thinking data rows) the same applies for the class just as Inferrd wrote.
Code:
Dim gList As List(Of getQueue) = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of getQueue))(MyJsonString)
What I do not understand is why use a class that when displayed in a DataGridView will not have the capabilities to sort (unless you have a custom comparer) via column headers in the DataGridView unless that is not a problem while using a DataTable is sortable
-
Aug 14th, 2013, 08:49 AM
#30
Re: JSON parsing
Originally Posted by michalss
...ERROR getting :
Code:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'pyLoad_GUI.getQueue' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
Don't want to beat a dead horse here - but the error message in your OP was clear. Told you that you had an ARRAY of OBJECTS - and even suggested making a LIST<T> to deal with it
-
Aug 14th, 2013, 08:49 AM
#31
Thread Starter
Addicted Member
Re: JSON parsing
What I do not understand is why use a class that when displayed in a DataGridView will not have the capabilities to sort (unless you have a custom comparer) via column headers in the DataGridView unless that is not a problem while using a DataTable is sortable
Not work try that before...
-
Aug 14th, 2013, 08:51 AM
#32
Thread Starter
Addicted Member
-
Aug 14th, 2013, 08:53 AM
#33
Re: JSON parsing
[QUOTE=michalss;4483511]
Originally Posted by kevininstructor
This i guess wont workt coz i try this allready, simple JSON format without dynamical arrays is always OK, but this strings contains combination of many objects and arrays
Where are the objects ???
Code:
[
{
"name":"X-men 1",
"links":null,
"dest":1,
"pid":18,
"site":"",
"linksdone":9,
"fids":null,
"sizetotal":9023234659,
"sizedone":9023234659,
"linkstotal":9,
"folder":"X-men 1",
"password":"",
"order":0
},
{
"name":"X-men 2",
"links":null,
"dest":1,
"pid":19,
"site":"",
"linksdone":13,
"fids":null,
"sizetotal":12774010166,
"sizedone":12774010166,
"linkstotal":13,
"folder":"X-men 2",
"password":"",
"order":1
},
{
"name":"X-men Origins",
"links":null,
"dest":1,
"pid":21,
"site":"",
"linksdone":10,
"fids":null,
"sizetotal":9810772035,
"sizedone":9810772035,
"linkstotal":10,
"folder":"X-men Origins",
"password":"",
"order":2
},
{
"name":"X-men 3 Last Stand",
"links":null,
"dest":1,
"pid":22,
"site":"",
"linksdone":13,
"fids":null,
"sizetotal":12376276378,
"sizedone":12376276378,
"linkstotal":13,
"folder":"X-men 3 Last Stand",
"password":"",
"order":3
}
]
-
Aug 14th, 2013, 08:53 AM
#34
Re: JSON parsing
My first experience with LIST's of DICTIONARIES of strings for JSON was a long learning curve - I can understand!
I wish I had seen your thread 2 days ago - I'm very aware of how JSON works now!
-
Aug 14th, 2013, 08:57 AM
#35
Re: JSON parsing
Somthing else to toss out, if you take the time to study how converters work including working with JArray is makes lifer easier.
-
Aug 14th, 2013, 09:03 AM
#36
Re: JSON parsing
Originally Posted by szlamany
My first experience with LIST's of DICTIONARIES of strings for JSON was a long learning curve - I can understand!
I wish I had seen your thread 2 days ago - I'm very aware of how JSON works now!
I went thru the pains of learning JSON a while back, the first thing I did was fully explore JSON.NET. Below are some of the things I did to understand what was going on under the covers
Code:
Imports Newtonsoft.Json.Linq
Imports Revenue.CultureLibrary
Public Module JArrayExtensions
''' <summary>
''' Populate sender with data either formatted or not formatted
''' </summary>
''' <param name="Sender"></param>
''' <param name="ItemArray"></param>
''' <param name="Format">Whether to format</param>
''' <remarks></remarks>
<System.Diagnostics.DebuggerStepThrough()> _
<System.Runtime.CompilerServices.Extension()> _
Public Sub Populate(ByRef Sender As JArray, ByVal ItemArray As Object(), ByVal Format As Boolean)
For Each item In ItemArray
If Format Then
If item.GetType Is GetType(Decimal) Then
Sender.Add(New JValue(Convert.ToInt32(item.ToString)))
ElseIf item.GetType Is GetType(Date) Then
Sender.Add(New JValue(Convert.ToDateTime(item).ToString(CurrentCultureShortDateFormat)))
Else
Sender.Add(New JValue(item))
End If
Else
Sender.Add(New JValue(item))
End If
Next
End Sub
''' <summary>
''' Used to return non-formatted data but does truncate the primary key to an integer.
''' </summary>
''' <param name="Sender"></param>
''' <param name="ItemArray"></param>
''' <remarks>
''' Assumes first field is the primary key.
''' </remarks>
<System.Diagnostics.DebuggerStepThrough()> _
<System.Runtime.CompilerServices.Extension()> _
Public Sub Populate(ByRef Sender As JArray, ByVal ItemArray As Object())
Dim PrimaryKey As Integer = 0
If Integer.TryParse(ItemArray(0).ToString, PrimaryKey) Then
Sender.Add(New JValue(PrimaryKey))
Else
Sender.Add(New JArray(ItemArray(0).ToString))
End If
For x As Integer = 1 To ItemArray.Count - 1
Sender.Add(New JValue(ItemArray(x)))
Next
End Sub
End Module
Code:
Public Module GeneralConverters
Public Function DataSetToJSON(ds As DataSet) As String
Dim dict As New Dictionary(Of String, Object)
For Each dt As DataTable In ds.Tables
Dim arr(dt.Rows.Count - 1) As Object
For i As Integer = 0 To dt.Rows.Count - 1
arr(i) = dt.Rows(i).ItemArray
Next
dict.Add(dt.TableName, arr)
Next
Dim json As New Web.Script.Serialization.JavaScriptSerializer
Return json.Serialize(dict)
End Function
<System.Diagnostics.DebuggerStepThrough()> _
<System.Runtime.CompilerServices.Extension()> _
Public Function DataTableToJSON(ByVal dt As DataTable) As String
If String.IsNullOrWhiteSpace(dt.TableName) Then
dt.TableName = "Dummy"
End If
Dim dict As New Dictionary(Of String, Object)
Dim RowData(dt.Rows.Count - 1) As Object
For i As Integer = 0 To dt.Rows.Count - 1
RowData(i) = dt.Rows(i).ItemArray
Next
dict.Add(dt.TableName, RowData)
Dim json As New Web.Script.Serialization.JavaScriptSerializer
Return json.Serialize(dict)
End Function
End Module
Code:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Data
''' <summary>
''' The default DataTable converter works fine, this converter shows
''' how to change default behavior by adding two attruibutes to the
''' JSON structure.
''' </summary>
''' <remarks></remarks>
Public Class RevenueSpecialDataTableConverter1
Inherits JsonConverter
''' <summary>
''' Indicates if operation went as expected
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Success As String = "FAILED"
Public Overrides Function CanConvert(ByVal objectType As System.Type) As Boolean
Return GetType(DataTable).IsAssignableFrom(objectType)
End Function
Public Overrides Function ReadJson(ByVal reader As Newtonsoft.Json.JsonReader, ByVal objectType As System.Type, ByVal existingValue As Object, ByVal serializer As Newtonsoft.Json.JsonSerializer) As Object
Dim jObject As JObject = jObject.Load(reader)
Dim dt As DataTable = New DataTable()
If jObject("TableName") IsNot Nothing Then
dt.TableName = jObject("TableName").ToString()
End If
If jObject("Columns") Is Nothing Then
Return dt
End If
If jObject("Rows") IsNot Nothing Then
For Each jRow As JArray In jObject("Rows")
Dim row As DataRow = dt.NewRow()
row.ItemArray = jRow.ToObject(Of System.Object())()
dt.Rows.Add(row)
Next
End If
Return dt
End Function
Public Overrides Sub WriteJson(ByVal writer As Newtonsoft.Json.JsonWriter, ByVal value As Object, ByVal serializer As Newtonsoft.Json.JsonSerializer)
Dim dt As DataTable = DirectCast(value, DataTable)
Dim resolver As Newtonsoft.Json.Serialization.DefaultContractResolver = TryCast(serializer.ContractResolver, Newtonsoft.Json.Serialization.DefaultContractResolver)
writer.WriteStartObject()
writer.WritePropertyName("resultCount")
writer.WriteValue(dt.Rows.Count)
writer.WritePropertyName("Status")
writer.WriteValue(Me.Success)
writer.WritePropertyName(dt.TableName)
writer.WriteStartArray()
For Each Row As DataRow In dt.Rows
writer.WriteStartObject()
For Each Column As DataColumn In Row.Table.Columns
If serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore AndAlso (Row(Column) Is Nothing _
OrElse TypeOf Row(Column) Is System.DBNull) Then
Continue For
End If
writer.WritePropertyName(Column.ColumnName)
serializer.Serialize(writer, Row(Column))
Next Column
writer.WriteEndObject()
Next Row
writer.WriteEndArray()
writer.WriteEndObject()
End Sub
End Class
Selective serialization
Code:
Imports Newtonsoft.Json
Imports System.Runtime.Serialization
Public Class DemoItem
Private da As SecretData = SecretData.GetInstance
Private mIdentifier As Int32
Public Property Identifier() As Int32
Get
Return mIdentifier
End Get
Set(ByVal value As Int32)
mIdentifier = value
End Set
End Property
Private mFirstName As String
Public Property FirstName() As String
Get
Return mFirstName
End Get
Set(ByVal value As String)
mFirstName = value
End Set
End Property
Private mSomeField As String
<JsonIgnore()> _
Public Property SomeField() As String
Get
Return mSomeField
End Get
Set(ByVal value As String)
mSomeField = value
End Set
End Property
Private mOregonTaxpayerID As String
Public Property OregonTaxpayerID() As String
Get
Return mOregonTaxpayerID
End Get
Set(ByVal value As String)
mOregonTaxpayerID = value
End Set
End Property
<OnSerializing()> _
Friend Sub OnSerializingMethod(ByVal context As StreamingContext)
If FirstName = "Kevin" Then
FirstName = "Was Kevin"
Else
FirstName = FirstName.ProperCase
End If
End Sub
<OnSerialized()> _
Friend Sub OnSerializedMethod(ByVal context As StreamingContext)
FirstName = "(FirstName) This value was reset after serialization."
End Sub
<OnDeserializing()> _
Friend Sub OnDeserializingMethod(ByVal context As StreamingContext)
SomeField = "(SomeField) This value was set during deserialization"
End Sub
<OnDeserialized()> _
Friend Sub OnDeserializedMethod(ByVal context As StreamingContext)
OregonTaxpayerID = da.List.Find(Function(x) x.Identifier = Identifier).OregonTaxpayerID
End Sub
Public Function ItemArray() As Object()
Return New Object() {FirstName, Identifier, SomeField, OregonTaxpayerID}
End Function
Public Overrides Function ToString() As String
Return FirstName
End Function
End Class
-
Aug 14th, 2013, 09:04 AM
#37
Thread Starter
Addicted Member
Re: JSON parsing
ehm im in shame now, but how can i now access the Links from this
Code:
Dim account As Main() = JsonConvert.DeserializeObject(Of Main())(ret)
Giving me list of all i need and i can access it, but link is Array in Array list, how can i access it and loop it please ?
ly
EDIT : never mind today im lost completely
Code:
Dim ddd = account(0).links(0).url
-
Aug 14th, 2013, 09:33 AM
#38
Re: JSON parsing
Originally Posted by kevininstructor
I went thru the pains of learning JSON a while back, the first thing I did was fully explore JSON.NET. Below are some of the things I did to understand what was going on under the covers
I work with browser apps - jQuery/JavaScript - talking to backend asp.net web methods - so the deserializing is done by IIS itself - I only have to make parameters in my methods that match the needed declarations.
And I've written my own "JSON serializer class" - quite a challenge - but worth it in the end for speed and what not...
JSON is now my friend
-
Aug 14th, 2013, 10:47 AM
#39
Thread Starter
Addicted Member
Re: JSON parsing
Is there any way how can VS 2010 autogenerated for me the class i need for parsing ? formlesstree4 said that VS did it for him but i dont know how and not sure if that is even possible ??
-
Aug 14th, 2013, 11:54 AM
#40
Re: JSON parsing
So what I came up with ... though I'm not sure whether it's still needed ...
vb.net Code:
Imports Newtonsoft.Json
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim js As New JsonSerializerSettings
js.CheckAdditionalContent = False
Dim ds = JsonConvert.DeserializeObject(Of List(Of VideoSpec))(IO.File.ReadAllText("C:\1.txt"), js)
For Each i In ds
TextBox1.AppendText(i.name & vbCrLf)
TextBox1.AppendText(i.links(0).name & vbCrLf & vbCrLf)
Next
End Sub
End Class
Class VidDetails
Public Property status As Integer
Public Property format_size As String
Public Property name As String
Public Property plugin As String
Public Property url As String
Public Property packageID As Integer
Public Property fid As Integer
Public Property [error] As String
Public Property statusmsg As String
Public Property order As Integer
Public Property size As Int64
End Class
Class VideoSpec
Private _fids As String = ""
Public Property name As String
Public Property links As VidDetails()
Public Property dest As Integer
Public Property pid As Integer
Public Property site As String
Public Property linksdone As Integer
Public Property fids As String
Get
Return _fids
End Get
Set(value As String)
If String.IsNullOrEmpty(value) Then _fids = "" Else _fids = value
End Set
End Property
Public Property sizetotal As Int64
Public Property sizedone As Int64
Public Property linkstotal As Object
Public Property folder As String
Public Property password As String
Public Property order As Integer
End Class
As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"
Reviews: "dunfiddlin likes his DataTables" - jmcilhinney
Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|