Android Question [SOLVED] - Extracting a value from downloaded JSON data

rleiman

Well-Known Member
Licensed User
Longtime User
Greetings,

I'm learning how to work with JSON and did a lot of searching and came up with the following coding. It's just a few lines of code but I thought it is at least enough to pull some data out of the downloaded data. I'm sure I messed up with the coding in several places and would like your help in getting me back on track.

The data is coming from This API.

Here is the coding I have so far:

B4X:
#Region  Project Attributes
    #ApplicationLabel: Test
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private xui As XUI
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Private Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
   
    Activity.LoadLayout("Layout")

    Try
       
        FetchJSON
    Catch
        Label1.Text = LastException
    End Try
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub FetchJSON() As ResumableSub

    Dim Job As HttpJob
    Job.Initialize(Null, Me)
    Job.Download("http://128.199.109.254/api/nowplaying")

    Wait For (Job) JobDone(Job As HttpJob)

    Label1.Text = "Job done success? " & Job.Success
   
    If Job.Success Then
        ToastMessageShow("Ready to parse.", True)
        Wait For (ParseJSONResults(Job.GetString)) Complete (Completed As Boolean)
    End If
    Job.Release

    Return True
End Sub

Sub ParseJSONResults(JSONResults As String) As ResumableSub
    Dim Parser As JSONParser
    Parser.Initialize(JSONResults)

    Dim TheRoot As Map = Parser.NextObject
    Label1.Text = "Text returned is: " & TheRoot.Get("title")

    Return True
End Sub

Processing never gets past the Job.Success line so I don't know why the job is not a success. That also means it never got to parse the JSON data.

I formatted the returned JSON data from the API in a formatter so it's easier to locate everything. The one field of data I'm interested in getting is under "title" which is nested under "now_playing". I'm not sure how to formulate my Get statement to grab that nested "title" value.

Here is the JSON from the API that I formatted:

B4X:
[
  {
    "station": {
      "id": 1,
      "name": "VIFM",
      "shortcode": "vifm",
      "description": "Gaya Hidup Anda",
      "frontend": "icecast",
      "backend": "liquidsoap",
      "listen_url": "http://128.199.109.254/radio/8000/128?1603494004",
      "is_public": true,
      "mounts": [
        {
          "path": "/320",
          "is_default": false,
          "id": 3,
          "name": "MP3 320KBPS",
          "url": "http://128.199.109.254/radio/8000/320?1603494004",
          "bitrate": 320,
          "format": "mp3",
          "listeners": {
            "current": 0,
            "unique": 0,
            "total": 0
          }
        },
        {
          "path": "/128",
          "is_default": true,
          "id": 4,
          "name": "MP3 128KBPS",
          "url": "http://128.199.109.254/radio/8000/128?1603494004",
          "bitrate": 128,
          "format": "mp3",
          "listeners": {
            "current": 0,
            "unique": 0,
            "total": 0
          }
        },
        {
          "path": "/64",
          "is_default": false,
          "id": 5,
          "name": "AAC+ 64KBPS",
          "url": "http://128.199.109.254/radio/8000/64?1603494004",
          "bitrate": 64,
          "format": "aac",
          "listeners": {
            "current": 1,
            "unique": 1,
            "total": 1
          }
        },
        {
          "path": "/32",
          "is_default": false,
          "id": 6,
          "name": "AAC+ 32KBPS",
          "url": "http://128.199.109.254/radio/8000/32?1603494004",
          "bitrate": 32,
          "format": "aac",
          "listeners": {
            "current": 0,
            "unique": 0,
            "total": 0
          }
        }
      ],
      "remotes": []
    },
    "listeners": {
      "current": 1,
      "unique": 1,
      "total": 1
    },
    "live": {
      "is_live": false,
      "streamer_name": "",
      "broadcast_start": null
    },
    "now_playing": {
      "elapsed": 80,
      "remaining": 200,
      "sh_id": 59999,
      "played_at": 1603493930,
      "duration": 280,
      "playlist": "default",
      "streamer": "",
      "is_request": false,
      "song": {
        "id": "2b7b5ec098f4cd99fbf5af2d30a31675",
        "text": "mawi - aduh saliha",
        "artist": "mawi",
        "title": "aduh saliha",
        "album": "",
        "lyrics": "",
        "art": "http://128.199.109.254/static/img/generic_song.jpg",
        "custom_fields": []
      }
    },
    "playing_next": {
      "sh_id": 60002,
      "played_at": 0,
      "duration": 264,
      "playlist": "default",
      "streamer": "",
      "is_request": false,
      "song": {
        "id": "2261ceda7266de58fec0cc0bd714b336",
        "text": "khalifah - mira",
        "artist": "khalifah",
        "title": "mira",
        "album": "",
        "lyrics": "",
        "art": "http://128.199.109.254/api/station/1/art/9a2d36a597950e71433845c8-1603112710.jpg",
        "custom_fields": []
      }
    },
    "song_history": [
      {
        "sh_id": 59997,
        "played_at": 1603493632,
        "duration": 211,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "70171ec85d4715d8179423e71a773869",
          "text": "2NE1 - I Am the Best (내가 제일 잘 나가)",
          "artist": "2NE1",
          "title": "I Am the Best (내가 제일 잘 나가)",
          "album": "2nd Mini Album",
          "lyrics": "",
          "art": "http://128.199.109.254/api/station/1/art/537d84f0d0a8c76bcd664f7f-1603086604.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59994,
        "played_at": 1603493425,
        "duration": 178,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "aadf26ccdc8af61a58b18fddb52d8eb2",
          "text": "aiman tino - ku hanya sayang padamu",
          "artist": "aiman tino",
          "title": "ku hanya sayang padamu",
          "album": "",
          "lyrics": "",
          "art": "http://128.199.109.254/static/img/generic_song.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59992,
        "played_at": 1603493092,
        "duration": 309,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "c76e4d85461c72238801cefc966851e0",
          "text": "ska 86 ft. kalia siska - seberkas sinar",
          "artist": "ska 86 ft. kalia siska",
          "title": "seberkas sinar",
          "album": "",
          "lyrics": "",
          "art": "http://128.199.109.254/static/img/generic_song.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59989,
        "played_at": 1603492884,
        "duration": 208,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "a29458834aecd87363067dd47e881b85",
          "text": "Billie Eilish - my future",
          "artist": "Billie Eilish",
          "title": "my future",
          "album": "my future",
          "lyrics": "",
          "art": "http://128.199.109.254/api/station/1/art/053dade261aa206961e6bc9a-1603091711.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59987,
        "played_at": 1603492657,
        "duration": 222,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "debd9f1d62379907956ac5d58dd80eae",
          "text": "tegar - aku mahu pacaran",
          "artist": "tegar",
          "title": "aku mahu pacaran",
          "album": "",
          "lyrics": "",
          "art": "http://128.199.109.254/static/img/generic_song.jpg",
          "custom_fields": []
        }
      }
    ],
    "cache": "station"
  }
]
 

Alex_197

Well-Known Member
Licensed User
Longtime User
Greetings,

I'm learning how to work with JSON and did a lot of searching and came up with the following coding. It's just a few lines of code but I thought it is at least enough to pull some data out of the downloaded data. I'm sure I messed up with the coding in several places and would like your help in getting me back on track.

The data is coming from This API.

Here is the coding I have so far:

B4X:
#Region  Project Attributes
    #ApplicationLabel: Test
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private xui As XUI
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Private Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
  
    Activity.LoadLayout("Layout")

    Try
      
        FetchJSON
    Catch
        Label1.Text = LastException
    End Try
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub FetchJSON() As ResumableSub

    Dim Job As HttpJob
    Job.Initialize(Null, Me)
    Job.Download("http://128.199.109.254/api/nowplaying")

    Wait For (Job) JobDone(Job As HttpJob)

    Label1.Text = "Job done success? " & Job.Success
  
    If Job.Success Then
        ToastMessageShow("Ready to parse.", True)
        Wait For (ParseJSONResults(Job.GetString)) Complete (Completed As Boolean)
    End If
    Job.Release

    Return True
End Sub

Sub ParseJSONResults(JSONResults As String) As ResumableSub
    Dim Parser As JSONParser
    Parser.Initialize(JSONResults)

    Dim TheRoot As Map = Parser.NextObject
    Label1.Text = "Text returned is: " & TheRoot.Get("title")

    Return True
End Sub

Processing never gets past the Job.Success line so I don't know why the job is not a success. That also means it never got to parse the JSON data.

I formatted the returned JSON data from the API in a formatter so it's easier to locate everything. The one field of data I'm interested in getting is under "title" which is nested under "now_playing". I'm not sure how to formulate my Get statement to grab that nested "title" value.

Here is the JSON from the API that I formatted:

B4X:
[
  {
    "station": {
      "id": 1,
      "name": "VIFM",
      "shortcode": "vifm",
      "description": "Gaya Hidup Anda",
      "frontend": "icecast",
      "backend": "liquidsoap",
      "listen_url": "http://128.199.109.254/radio/8000/128?1603494004",
      "is_public": true,
      "mounts": [
        {
          "path": "/320",
          "is_default": false,
          "id": 3,
          "name": "MP3 320KBPS",
          "url": "http://128.199.109.254/radio/8000/320?1603494004",
          "bitrate": 320,
          "format": "mp3",
          "listeners": {
            "current": 0,
            "unique": 0,
            "total": 0
          }
        },
        {
          "path": "/128",
          "is_default": true,
          "id": 4,
          "name": "MP3 128KBPS",
          "url": "http://128.199.109.254/radio/8000/128?1603494004",
          "bitrate": 128,
          "format": "mp3",
          "listeners": {
            "current": 0,
            "unique": 0,
            "total": 0
          }
        },
        {
          "path": "/64",
          "is_default": false,
          "id": 5,
          "name": "AAC+ 64KBPS",
          "url": "http://128.199.109.254/radio/8000/64?1603494004",
          "bitrate": 64,
          "format": "aac",
          "listeners": {
            "current": 1,
            "unique": 1,
            "total": 1
          }
        },
        {
          "path": "/32",
          "is_default": false,
          "id": 6,
          "name": "AAC+ 32KBPS",
          "url": "http://128.199.109.254/radio/8000/32?1603494004",
          "bitrate": 32,
          "format": "aac",
          "listeners": {
            "current": 0,
            "unique": 0,
            "total": 0
          }
        }
      ],
      "remotes": []
    },
    "listeners": {
      "current": 1,
      "unique": 1,
      "total": 1
    },
    "live": {
      "is_live": false,
      "streamer_name": "",
      "broadcast_start": null
    },
    "now_playing": {
      "elapsed": 80,
      "remaining": 200,
      "sh_id": 59999,
      "played_at": 1603493930,
      "duration": 280,
      "playlist": "default",
      "streamer": "",
      "is_request": false,
      "song": {
        "id": "2b7b5ec098f4cd99fbf5af2d30a31675",
        "text": "mawi - aduh saliha",
        "artist": "mawi",
        "title": "aduh saliha",
        "album": "",
        "lyrics": "",
        "art": "http://128.199.109.254/static/img/generic_song.jpg",
        "custom_fields": []
      }
    },
    "playing_next": {
      "sh_id": 60002,
      "played_at": 0,
      "duration": 264,
      "playlist": "default",
      "streamer": "",
      "is_request": false,
      "song": {
        "id": "2261ceda7266de58fec0cc0bd714b336",
        "text": "khalifah - mira",
        "artist": "khalifah",
        "title": "mira",
        "album": "",
        "lyrics": "",
        "art": "http://128.199.109.254/api/station/1/art/9a2d36a597950e71433845c8-1603112710.jpg",
        "custom_fields": []
      }
    },
    "song_history": [
      {
        "sh_id": 59997,
        "played_at": 1603493632,
        "duration": 211,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "70171ec85d4715d8179423e71a773869",
          "text": "2NE1 - I Am the Best (내가 제일 잘 나가)",
          "artist": "2NE1",
          "title": "I Am the Best (내가 제일 잘 나가)",
          "album": "2nd Mini Album",
          "lyrics": "",
          "art": "http://128.199.109.254/api/station/1/art/537d84f0d0a8c76bcd664f7f-1603086604.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59994,
        "played_at": 1603493425,
        "duration": 178,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "aadf26ccdc8af61a58b18fddb52d8eb2",
          "text": "aiman tino - ku hanya sayang padamu",
          "artist": "aiman tino",
          "title": "ku hanya sayang padamu",
          "album": "",
          "lyrics": "",
          "art": "http://128.199.109.254/static/img/generic_song.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59992,
        "played_at": 1603493092,
        "duration": 309,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "c76e4d85461c72238801cefc966851e0",
          "text": "ska 86 ft. kalia siska - seberkas sinar",
          "artist": "ska 86 ft. kalia siska",
          "title": "seberkas sinar",
          "album": "",
          "lyrics": "",
          "art": "http://128.199.109.254/static/img/generic_song.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59989,
        "played_at": 1603492884,
        "duration": 208,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "a29458834aecd87363067dd47e881b85",
          "text": "Billie Eilish - my future",
          "artist": "Billie Eilish",
          "title": "my future",
          "album": "my future",
          "lyrics": "",
          "art": "http://128.199.109.254/api/station/1/art/053dade261aa206961e6bc9a-1603091711.jpg",
          "custom_fields": []
        }
      },
      {
        "sh_id": 59987,
        "played_at": 1603492657,
        "duration": 222,
        "playlist": "default",
        "streamer": "",
        "is_request": false,
        "song": {
          "id": "debd9f1d62379907956ac5d58dd80eae",
          "text": "tegar - aku mahu pacaran",
          "artist": "tegar",
          "title": "aku mahu pacaran",
          "album": "",
          "lyrics": "",
          "art": "http://128.199.109.254/static/img/generic_song.jpg",
          "custom_fields": []
        }
      }
    ],
    "cache": "station"
  }
]
check this out http://basic4ppc.com:51042/json/index.html - it will create a vb code to parse your json
 
Upvote 0

Alex_197

Well-Known Member
Licensed User
Longtime User
At least that part is now solved. :)

Can you tell why the processing is not getting past the Job.Success line?

First of all - what if job is not success?

Second why do you need another wait for?


B4X:
If Job.Success Then
        ToastMessageShow("Ready to parse.", True)
        Wait For (ParseJSONResults(Job.GetString)) Complete (Completed As Boolean)
    End If

Why not just call it like
B4X:
If Job.Success Then
Dim IsOk as boolean=False
        ToastMessageShow("Ready to parse.", True)
        IsOk=ParseJSONResults(Job.GetString)
    End If
    
Private Sub ParseJSONResults(KSONStr as string)

try
'do your parse
return true
Catch
return false
end try


end Sub
 
Upvote 0

rleiman

Well-Known Member
Licensed User
Longtime User
I also tri
I will also go through that tutorial to learn the proper use for Wait For.

I also tried to place the a JSON file with the code from the API as a text JSON file but my try catch responds with "Expected literal value at character 1" I know that file is valid because I ran it through a formatter that also validates the JSON as valid. Maybe the API is not supplying the literal value but I don't know what value should be there.
 
Upvote 0

rleiman

Well-Known Member
Licensed User
Longtime User
I just found an old tutorial on JSON at https://www.b4x.com/android/forum/threads/android-json-tutorial.6923/#content

I also used the text editor to paste the sample JSON string to a .json file and imported it into my project from the files tab. When I run the code to parse the file I still get that "Expected literal value at character 1" error. What is this literal value they want? I need to be able to get success with that tutorial before I can move on.

Thanks.
 
Upvote 0

Alex_197

Well-Known Member
Licensed User
Longtime User
I also tri

I will also go through that tutorial to learn the proper use for Wait For.

I also tried to place the a JSON file with the code from the API as a text JSON file but my try catch responds with "Expected literal value at character 1" I know that file is valid because I ran it through a formatter that also validates the JSON as valid. Maybe the API is not supplying the literal value but I don't know what value should be there.
check this - I created a small project
 

Attachments

  • JSONAPI.zip
    9.7 KB · Views: 343
Upvote 0

rleiman

Well-Known Member
Licensed User
Longtime User
Thanks for everyone's help. With your guidance I was able to download the JSON data and parse it to extract the song title and artist's name with this coding I added to the attached project and parsing tool from Alex.

B4X:
Private Sub ParseJSONResults(JobString As String)
    
    txtJSON.Text = ""
    
    Try
        
        Dim parser As JSONParser
        parser.Initialize(JobString)

        Dim root As List = parser.NextArray
        Dim colroot As Map = root.Get("0")
        Dim now_playing As Map = colroot.Get("now_playing")
        Dim song As Map = now_playing.Get("song")
        Dim songTitle As String = song.Get("title")
        Dim artist As String = song.Get("artist")

        txtJSON.Text = txtJSON.Text & "The Artist is " & artist & "." & Chr(10)
        txtJSON.Text = txtJSON.Text & "The song title is " & songTitle & "." & Chr(10)

    Catch
        Log(LastException)
    End Try
End Sub
 
Upvote 0
Top