Results 1 to 19 of 19

Thread: [RESOLVED] JSON to ....

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2006
    Location
    UK / East Sussex
    Posts
    1,054

    Resolved [RESOLVED] JSON to ....

    Afternoon Everyone,

    I have been working on this app for awhile now and most of the inputs I have had to read are XML which are all working very nicely however there is something I have never come acrss before apart from hearing of it I have never had any interaction with it and that is JSON!

    I have been looking on the net for over an hour and I am completly lost at how to translate from JSON so I can use values contained within it. More specifically I am trying to query the Apply itune stores database for track information. Here is an example of one of the returned JSON strings:

    Code:
    
    {
     "resultCount":1,
     "results": [
    {"wrapperType":"track", "kind":"song", "artistId":255772678, "collectionId":270137469, "trackId":270137520, "artistName":"Hadouken!", "collectionName":"Love, Sweat and Beer - EP", "trackName":"Girls", "collectionCensoredName":"Love, Sweat and Beer - EP", "trackCensoredName":"Girls", "artistViewUrl":"https://itunes.apple.com/gb/artist/hadouken!/id255772678?uo=4", "collectionViewUrl":"https://itunes.apple.com/gb/album/girls/id270137469?i=270137520&uo=4", "trackViewUrl":"https://itunes.apple.com/gb/album/girls/id270137469?i=270137520&uo=4", "previewUrl":"http://a717.phobos.apple.com/us/r1000/113/Music/b2/e8/f8/mzm.xrpvmzgz.aac.p.m4a", "artworkUrl30":"http://a176.phobos.apple.com/us/r1000/040/Music/20/98/3c/mzi.azgszqgw.30x30-50.jpg", "artworkUrl60":"http://a240.phobos.apple.com/us/r1000/040/Music/20/98/3c/mzi.azgszqgw.60x60-50.jpg", "artworkUrl100":"http://a1585.phobos.apple.com/us/r1000/040/Music/20/98/3c/mzi.azgszqgw.100x100-75.jpg", "collectionPrice":1.99, "trackPrice":0.79, "releaseDate":"2007-12-24T08:00:00Z", "collectionExplicitness":"notExplicit", "trackExplicitness":"notExplicit", "discCount":1, "discNumber":1, "trackCount":4, "trackNumber":3, "trackTimeMillis":205973, "country":"GBR", "currency":"GBP", "primaryGenreName":"Alternative"}]
    }
    This can be seen for yourself by entering https://itunes.apple.com/search?term...=music&limit=1 into your browser (works on firefox but I am told IE tries to download it as a file)

    Now I need to get quite a few bits of information out of this JSON return but I have no idea how to go about it. I have seen a few things online that can convert it to a custom object also heard an Array. The other option I have heard is converting it to XML and I would be more than happy to have it in XML as I know exactly how to query that but to be honest I don't care how its stored within the application as long as I can read each attribute as and when I need it.

    So for instance it would be nice to do something like

    Dim Artist as string = jsonobj(jsoninput, "artistName")

    which from the above JSON example my string would contain "Hadouken!"

    Has anyone had any dealing with JSON and please be able to provide me some advice because I have tried a couple of libraries but im stabbing in the dark nothing I have read has made any sense.

    Thanks,
    Max
    M.Carpenter

    Server Admin for Wurm Online
    Wurm Online - A very unique and original MMO from Code Club AB
    https://www.youtube.com/watch?v=YQlYar2uHWAWurm Trailor


  2. #2
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,764
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,350

    Re: JSON to ....

    Look at the JavaScriptSerializer class.

  4. #4
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: JSON to ....

    You need to use a JSON serialiser to deserialise it. I think the default choice in .NET is JSON.Net

  5. #5
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,481

    Re: JSON to ....

    you can read it with a JavaScriptSerializer:

    Code:
    Public Class JSON_resultArray
        Public results() As JSON_result
    End Class
    Code:
    Public Class JSON_result
        Public wrapperType As String
        Public kind As String
        Public artistName As String
        Public collectionName As String
        Public trackName As String
        Public collectionCensoredName As String
        Public trackCensoredName As String
        Public artistViewUrl As String
        Public collectionViewUrl As String
        Public trackViewUrl As String
        Public previewUrl As String
        Public artworkUrl30 As String
        Public artworkUrl60 As String
        Public artworkUrl100 As String
        Public releaseDate As String
        Public collectionExplicitness As String
        Public trackExplicitness As String
        Public country As String
        Public currency As String
        Public primaryGenreName As String
    End Class
    Code:
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim json = TextBox1.Text
    
            Dim ser As New System.Web.Script.Serialization.JavaScriptSerializer
            Dim results As JSON_resultArray = DirectCast(ser.Deserialize(Of JSON_resultArray)(json), JSON_resultArray)
            Stop
        End Sub
    
    End Class
    edit: too slow

  6. #6

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2006
    Location
    UK / East Sussex
    Posts
    1,054

    Re: JSON to ....

    I have been looking at documents like this but that's whats getting me confused I have never done serialization etc. I have this code:

    Code:
            Dim json As String
            Dim reader As StreamReader = New StreamReader("C:\json.txt")
            json = reader.ReadToEnd
            reader.Close()
    
    
            Dim obj As New List(Of ApplicationItem)()
            Dim ms As New MemoryStream(Encoding.Unicode.GetBytes(json))
            Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.[GetType]())
            obj = DirectCast(serializer.ReadObject(ms), List(Of ApplicationItem))
            ms.Close()
            ms.Dispose()
    which runs with no errors but how to I read the individual attributes still? By the was json.txt contains the json I posted in the first post.

    As for the JavaScriptSerializer jmcil I have no idea to even where begin with this its not reconised and I have no clue what needs to be referenced...

    Regards,
    Max
    M.Carpenter

    Server Admin for Wurm Online
    Wurm Online - A very unique and original MMO from Code Club AB
    https://www.youtube.com/watch?v=YQlYar2uHWAWurm Trailor


  7. #7

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2006
    Location
    UK / East Sussex
    Posts
    1,054

    Re: JSON to ....

    Thanks for the code paul but I am still getting the below error with nothing obvious to import or reference:

    Name:  1.jpg
Views: 9898
Size:  87.8 KB
    M.Carpenter

    Server Admin for Wurm Online
    Wurm Online - A very unique and original MMO from Code Club AB
    https://www.youtube.com/watch?v=YQlYar2uHWAWurm Trailor


  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,481

    Re: JSON to ....

    add a reference to:

    System.Web.Extensions

  9. #9

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2006
    Location
    UK / East Sussex
    Posts
    1,054

    Re: JSON to ....

    Am I being a complete idiot today or is something missing (don't be afraid to be honest)

    Name:  2.jpg
Views: 9509
Size:  103.4 KB
    M.Carpenter

    Server Admin for Wurm Online
    Wurm Online - A very unique and original MMO from Code Club AB
    https://www.youtube.com/watch?v=YQlYar2uHWAWurm Trailor


  10. #10
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,481

    Re: JSON to ....

    which version of vb are you using?

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,350

    Re: JSON to ....

    Advanced web functionality is not included in the Client Profile. You'll need to target the full Framework.

  12. #12
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,481

    Re: JSON to ....

    actually scrub that. it's obviously vb2010 or greater.
    i found it in vb2012 + i can't find it in vb2010 either...

    sorry. someone else might have a solution.

  13. #13

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2006
    Location
    UK / East Sussex
    Posts
    1,054

    Re: JSON to ....

    Well done jmcil as per normal :-) Didn't even realise that. Ok Im targetting the full framework now and have imported system.web.extensions and no errors with the code now. Now just need to know how to actualy grab the results...
    M.Carpenter

    Server Admin for Wurm Online
    Wurm Online - A very unique and original MMO from Code Club AB
    https://www.youtube.com/watch?v=YQlYar2uHWAWurm Trailor


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

    Re: JSON to ....

    After I did a lot of research I found JSON.NET to be more inline with our web team who is non-Microsoft.

  15. #15

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2006
    Location
    UK / East Sussex
    Posts
    1,054

    Re: JSON to ....

    I did take a brief look at JSON.Net before I posted but it seemed overly complex for what I needed I just want a really simple way of converting a relatively basic JSON to something I can read and the code that paul has paste seems like it will do the trick nicely but I am just trying to figure out how to read each of the values now. Doesn't help I am trying to do it inbetween support calls but I just can't see what im doing.
    M.Carpenter

    Server Admin for Wurm Online
    Wurm Online - A very unique and original MMO from Code Club AB
    https://www.youtube.com/watch?v=YQlYar2uHWAWurm Trailor


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

    Re: JSON to ....

    Here is JSON.NET example using a string to read into a class and one example reading from disk. Follow my lead to complete.
    Must of course download the library

    Code:
    Imports Newtonsoft.Json
    Imports Newtonsoft.Json.Schema
    Imports Newtonsoft.Json.Linq
    Module Module1
        Public Sub ParseFromString()
            Dim Contents As String = IO.File.ReadAllText(IO.Path.Combine(Application.StartupPath, "TextFile1.txt"))
    
            Dim DocObject = JObject.Parse(Contents)
            Try
    
                Dim ResultCount As Integer = CInt(DocObject("resultCount"))
                If ResultCount > 0 Then
                    '
                    ' Yeah I realize there is only one but we are demoing count with hopes
                    ' the count indicates how many rows/records are being pushed in.
                    '
                    For x As Integer = 0 To ResultCount - 1
                        Console.WriteLine("[{0}] [{1}]", x + 1, CStr(DocObject("results")(x)("artistName")))
                    Next
    
                    Console.WriteLine("-----------------------------")
    
                    Dim Test1 =
                        (
                            From T In DocObject("results").Children
                            Select New AppleRecord With
                                   {
                                       .WrapperType = T("wrapperType").ToString,
                                       .Kind = T("kind").ToString,
                                       .ArtistId = CInt(T("artistId")),
                                       .CollectionName = T("collectionName").ToString,
                                       .PreviewUrl = T("previewUrl").ToString
                                   }
                               ).ToList
    
                    For Each item As AppleRecord In Test1
                        Console.WriteLine("[{0}] [{1}] [{2}] [{3}] [{4}]",
                                          item.WrapperType,
                                          item.Kind,
                                          item.ArtistId,
                                          item.CollectionName,
                                          item.PreviewUrl
                                          )
                    Next
                Else
                    Console.WriteLine("No records")
                End If
    
            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try
    
    
    
        End Sub
        Public Sub ReadFromFile()
    
            Using reader As IO.StreamReader = IO.File.OpenText(IO.Path.Combine(Application.StartupPath, "TextFile1.txt"))
    
                Dim DocObject As JObject = CType(JToken.ReadFrom(New JsonTextReader(reader)), JObject)
    
                Try
                    Dim ResultCount As Integer = CInt(DocObject("resultCount"))
                    If ResultCount > 0 Then
                        '
                        ' Yeah I realize there is only one but we are demoing count with hopes
                        ' the count indicates how many rows/records are being pushed in.
                        '
                        For x As Integer = 0 To ResultCount - 1
                            Console.WriteLine("[{0}] [{1}]", x + 1, CStr(DocObject("results")(x)("artistName")))
                        Next
    
                        Console.WriteLine("-----------------------------")
    
                        Dim Test1 =
                            (
                                From T In DocObject("results").Children
                                Select New AppleRecord With
                                       {
                                           .WrapperType = T("wrapperType").ToString,
                                           .Kind = T("kind").ToString,
                                           .ArtistId = CInt(T("artistId")),
                                           .CollectionName = T("collectionName").ToString,
                                           .PreviewUrl = T("previewUrl").ToString
                                       }
                                   ).ToList
    
                        For Each item As AppleRecord In Test1
                            Console.WriteLine("[{0}] [{1}] [{2}] [{3}] [{4}]",
                                              item.WrapperType,
                                              item.Kind,
                                              item.ArtistId,
                                              item.CollectionName,
                                              item.PreviewUrl
                                              )
                        Next
                    Else
                        Console.WriteLine("No records")
                    End If
    
                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                End Try
    
    
            End Using
    
        End Sub
        Public Class AppleRecord
            Public Property WrapperType() As String
            Public Property Kind() As String
            Public Property ArtistId() As Integer
            Public Property CollectionId() As Integer
            Public Property TrackId() As Integer
            Public Property ArtistName() As String
            Public Property CollectionName() As String
            Public Property TrackName() As String
            Public Property CollectionCensoredName() As String
            Public Property TrackCensoredName() As String
            Public Property ArtistViewUrl() As String
            Public Property CollectionViewUrl() As String
            Public Property TrackViewUrl() As String
            Public Property PreviewUrl() As String
            Public Property ArtworkUrl30() As String
            Public Property ArtworkUrl60() As String
            Public Property ArtworkUrl100() As String
            Public Property CollectionPrice() As Double
            Public Property TrackPrice() As Double
            Public Property ReleaseDate() As String
            Public Property CollectionExplicitness() As String
            Public Property TrackExplicitness() As String
            Public Property DiscCount() As Integer
            Public Property DiscNumber() As Integer
            Public Property TrackCount() As Integer
            Public Property TrackNumber() As Integer
            Public Property TrackTimeMillis() As Integer
            Public Property Country() As String
            Public Property Currency() As String
            Public Property PrimaryGenreName() As String
            Public Sub New()
            End Sub
        End Class
    End Module

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

    Re: JSON to ....

    As per my last reply, here is the JSON which I formatted via JSON.NET methods
    Code:
    {
      "resultCount": 1,
      "results": [
        {
          "wrapperType": "track",
          "kind": "song",
          "artistId": 255772678,
          "collectionId": 270137469,
          "trackId": 270137520,
          "artistName": "Hadouken!",
          "collectionName": "Love, Sweat and Beer - EP",
          "trackName": "Girls",
          "collectionCensoredName": "Love, Sweat and Beer - EP",
          "trackCensoredName": "Girls",
          "artistViewUrl": "https://itunes.apple.com/gb/artist/hadouken!/id255772678?uo=4",
          "collectionViewUrl": "https://itunes.apple.com/gb/album/girls/id270137469?i=270137520&uo=4",
          "trackViewUrl": "https://itunes.apple.com/gb/album/girls/id270137469?i=270137520&uo=4",
          "previewUrl": "http://a717.phobos.apple.com/us/r1000/113/Music/b2/e8/f8/mzm.xrpvmzgz.aac.p.m4a",
          "artworkUrl30": "http://a176.phobos.apple.com/us/r1000/040/Music/20/98/3c/mzi.azgszqgw.30x30-50.jpg",
          "artworkUrl60": "http://a240.phobos.apple.com/us/r1000/040/Music/20/98/3c/mzi.azgszqgw.60x60-50.jpg",
          "artworkUrl100": "http://a1585.phobos.apple.com/us/r1000/040/Music/20/98/3c/mzi.azgszqgw.100x100-75.jpg",
          "collectionPrice": 1.99,
          "trackPrice": 0.79,
          "releaseDate": "2007-12-24T08:00:00Z",
          "collectionExplicitness": "notExplicit",
          "trackExplicitness": "notExplicit",
          "discCount": 1,
          "discNumber": 1,
          "trackCount": 4,
          "trackNumber": 3,
          "trackTimeMillis": 205973,
          "country": "GBR",
          "currency": "GBP",
          "primaryGenreName": "Alternative"
        }
      ]
    }

  18. #18

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2006
    Location
    UK / East Sussex
    Posts
    1,054

    Re: JSON to ....

    Apologies for being half asleep yesterday its all resolved now much easier than using that json.net library. Thanks to everyone that has helped here is the end Result:

    Code:
    Public Class JSON_result
        Public wrapperType As String
        Public kind As String
        Public artistName As String
        Public collectionName As String
        Public trackName As String
        Public collectionCensoredName As String
        Public trackCensoredName As String
        Public artistViewUrl As String
        Public collectionViewUrl As String
        Public trackViewUrl As String
        Public previewUrl As String
        Public artworkUrl30 As String
        Public artworkUrl60 As String
        Public artworkUrl100 As String
        Public releaseDate As String
        Public collectionExplicitness As String
        Public trackExplicitness As String
        Public country As String
        Public currency As String
        Public primaryGenreName As String
    End Class
    Code:
    Public Class JSON_resultArray
        Public Vars() As JSON_result
    End Class
    Code:
    Sub Main()
    
            Dim ser As New System.Web.Script.Serialization.JavaScriptSerializer
            Dim results As JSON_resultArray = DirectCast(ser.Deserialize(Of JSON_resultArray)(json), JSON_resultArray)
    
    
            Console.WriteLine(results.Vars(0).artistName)
            Console.WriteLine(results.Vars(0).collectionName)
    
    End Sub
    M.Carpenter

    Server Admin for Wurm Online
    Wurm Online - A very unique and original MMO from Code Club AB
    https://www.youtube.com/watch?v=YQlYar2uHWAWurm Trailor


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

    Re: [RESOLVED] JSON to ....

    Hello, you really should check resultCount as a general rule of thumb, no different than checking the Count property of a DataTable. For example, if there are no items the index would be out of range. At best check how many items are in Vars()

    Code:
    Console.WriteLine(results.Vars(0).artistName)
    What we do is (although not done here) besides a count is a success field/element which indicates a record or records are valid for a given operation which I have seen often when working with partner's data.

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