Page 1 of 2 12 LastLast
Results 1 to 40 of 43

Thread: JSON parsing

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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

  2. #2
    Frenzied Member
    Join Date
    Feb 2008
    Location
    Texas
    Posts
    1,288

    Re: JSON parsing

    Looks like you have an array or list of getQueue objects (represented in the JSON).

    VB Code:
    1. Dim account as List(of getQueue) = JsonConvert.DeserializeObject(Of getQueue)(ret) ' maybe?
    2. 'or
    3. Dim account as getQueue() = JsonConvert.DeserializeObject(Of getQueue)(ret)
    You down with OOP? Yeah you know me!
    MCAD and MCMICKEYMOUSE (vb.net)

    ----

    If it even kinda helps... rate it : )

    Edit a Multi-page .tif file and save.

  3. #3
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: JSON parsing

    Well it all rather depends on what 'getQueue' is does it not? This ....

    vb.net Code:
    1. Dim account As DataTable = JsonConvert.DeserializeObject(Of DataTable)(ret)
    2.         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!

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Quote Originally Posted by dunfiddlin View Post
    Well it all rather depends on what 'getQueue' is does it not? This ....

    vb.net Code:
    1. Dim account As DataTable = JsonConvert.DeserializeObject(Of DataTable)(ret)
    2.         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

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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 ??

  6. #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.

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Nope nothing chanage, still same error im getting damn im so frustrated

  8. #8
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    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!

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Quote Originally Posted by dunfiddlin View Post
    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

  10. #10

    Re: JSON parsing

    Quote Originally Posted by dunfiddlin View Post
    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

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    anyone please ?

  12. #12
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Quote Originally Posted by szlamany View Post
    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

  14. #14
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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)

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Quote Originally Posted by szlamany View Post
    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
    "

  16. #16
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: JSON parsing

    Add this and see if it works...

    Imports System.Collections.Generic

    Otherwise see if changing ILIST to LIST works...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  17. #17
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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)

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  18. #18
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  19. #19

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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]].

  20. #20
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: JSON parsing

    That says they use LIST internally - so ILIST won't work.

    Change it to LIST(of...)

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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.

  22. #22
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: JSON parsing

    Did you see my post #20??

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  23. #23

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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.

  24. #24
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: JSON parsing

    How about

    List(Of getQueue)

    Since that's ultimately where you want it to go...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  25. #25
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,335

    Re: JSON parsing

    I think MonkOFox was quite close:

    Quote Originally Posted by MonkOFox View Post
    VB Code:
    1. Dim account as List(of getQueue) = JsonConvert.DeserializeObject(Of getQueue)(ret) ' maybe?
    2. 'or
    3. 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)

  26. #26

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Quote Originally Posted by Inferrd View Post
    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

  27. #27
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: JSON parsing

    Quote Originally Posted by szlamany View Post
    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?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  28. #28

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Quote Originally Posted by szlamany View Post
    And how is that different then what is posted here?

    You have been right as well, i' just an idiot Sorry mate

  29. #29
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,686

    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

  30. #30
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: JSON parsing

    Quote Originally Posted by michalss View Post
    ...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

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  31. #31

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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...

  32. #32

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    Re: JSON parsing

    Quote Originally Posted by szlamany View Post
    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

    Yes you right this is my first time to dealing with JSON ever and i guess i just simple miss that one or i was not clever enough to release it . Thx all again boys i hope i can manage it from there

  33. #33
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,686

    Re: JSON parsing

    [QUOTE=michalss;4483511]
    Quote Originally Posted by kevininstructor View Post
    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
       }
    ]

  34. #34
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  35. #35
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,686

    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.

  36. #36
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,686

    Re: JSON parsing

    Quote Originally Posted by szlamany View Post
    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

  37. #37

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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

  38. #38
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: JSON parsing

    Quote Originally Posted by kevininstructor View Post
    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

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  39. #39

    Thread Starter
    Addicted Member
    Join Date
    Jan 2008
    Posts
    162

    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 ??

  40. #40
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: JSON parsing

    So what I came up with ... though I'm not sure whether it's still needed ...

    vb.net Code:
    1. Imports Newtonsoft.Json
    2.  
    3. Public Class Form1
    4.  
    5.     Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    6.  
    7.         Dim js As New JsonSerializerSettings
    8.         js.CheckAdditionalContent = False
    9.         Dim ds = JsonConvert.DeserializeObject(Of List(Of VideoSpec))(IO.File.ReadAllText("C:\1.txt"), js)
    10.         For Each i In ds
    11.             TextBox1.AppendText(i.name & vbCrLf)
    12.             TextBox1.AppendText(i.links(0).name & vbCrLf & vbCrLf)
    13.         Next
    14.  
    15.     End Sub
    16. End Class
    17.  
    18. Class VidDetails
    19.     Public Property status As Integer
    20.     Public Property format_size As String
    21.     Public Property name As String
    22.     Public Property plugin As String
    23.     Public Property url As String
    24.     Public Property packageID As Integer
    25.     Public Property fid As Integer
    26.     Public Property [error] As String
    27.     Public Property statusmsg As String
    28.     Public Property order As Integer
    29.     Public Property size As Int64
    30. End Class
    31.  
    32. Class VideoSpec
    33.     Private _fids As String = ""
    34.  
    35.     Public Property name As String
    36.     Public Property links As VidDetails()
    37.     Public Property dest As Integer
    38.     Public Property pid As Integer
    39.     Public Property site As String
    40.     Public Property linksdone As Integer
    41.     Public Property fids As String
    42.         Get
    43.             Return _fids
    44.         End Get
    45.         Set(value As String)
    46.             If String.IsNullOrEmpty(value) Then _fids = "" Else _fids = value
    47.         End Set
    48.     End Property
    49.     Public Property sizetotal As Int64
    50.     Public Property sizedone As Int64
    51.     Public Property linkstotal As Object
    52.     Public Property folder As String
    53.     Public Property password As String
    54.     Public Property order As Integer
    55.  
    56. 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!

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width