Android Question Parse JSON string

ThePuiu

Active Member
Licensed User
Longtime User
Hi,
My server returns the following string:
B4X:
{"id":"1","Numar":"1","TextIntrebare":"Cate anotimpuri are un an?","Punctaj":"10","Blocata":"0","Raspunsuri":[{"id":"1","idIntrebare":"1","Raspuns":"1","Corect":"0","Blocat":"0"},{"id":"2","idIntrebare":"1","Raspuns":"3","Corect":"0","Blocat":"0"},{"id":"3","idIntrebare":"1","Raspuns":"4","Corect":"1","Blocat":"0"}]}
Which I'm trying to decode using the following code:
B4X:
Dim intrebare As String = "[{\""id\"":\""1\"",\""Numar\"":\""1\"",\""TextIntrebare\"":\""Cate anotimpuri are un an?\"",\""Punctaj\"":\""10\"",\""Blocata\"":\""0\"",\""Raspunsuri\"":[{\""id\"":\""1\"",\""idIntrebare\"":\""1\"",\""Raspuns\"":\""1\"",\""Corect\"":\""0\"",\""Blocat\"":\""0\""},{\""id\"":\""2\"",\""idIntrebare\"":\""1\"",\""Raspuns\"":\""3\"",\""Corect\"":\""0\"",\""Blocat\"":\""0\""},{\""id\"":\""3\"",\""idIntrebare\"":\""1\"",\""Raspuns\"":\""4\"",\""Corect\"":\""1\"",\""Blocat\"":\""0\""}]}]"

Dim Lista As Map
Dim JSON As JSONParser
JSON.Initialize(intrebare)
Lista = JSON.NextArray
But I receive the error message:
org.json.JSONException: Expected literal value at character 1 of {\"id\":\"1\",\"Numar\":\"1\",\"TextIntrebare\":\"Cate anotimpuri are un an?\",\"Punctaj\":\"10\",\"Blocata\":\"0\",\"Raspunsuri\":[{\"id\":\"1\",\"idIntrebare\":\"1\",\"Raspuns\":\"1\",\"Corect\":\"0\",\"Blocat\":\"0\"},{\"id\":\"2\",\"idIntrebare\":\"1\",\"Raspuns\":\"3\",\"Corect\":\"0\",\"Blocat\":\"0\"},{\"id\":\"3\",\"idIntrebare\":\"1\",\"Raspuns\":\"4\",\"Corect\":\"1\",\"Blocat\":\"0\"}]}

In what form should the string be received from the server?
Thank you!
 

NJDude

Expert
Licensed User
Longtime User
Try this code:

B4X:
Private jParser As JSONParser

jParser.Initialize(JSONText)

Private Root As Map = jParser.NextObject
Private Blocata As String = Root.Get("Blocata")
Private Punctaj As String = Root.Get("Punctaj")
Private Numar As String = Root.Get("Numar")
Private id As String = Root.Get("id")
Private TextIntrebare As String = Root.Get("TextIntrebare")
Private Raspunsuri As List = Root.Get("Raspunsuri")

For Each ColRaspunsuri As Map In Raspunsuri

    Private Raspuns As String = ColRaspunsuri.Get("Raspuns")
    Private idIntrebare As String = ColRaspunsuri.Get("idIntrebare")
    Private Blocat As String = ColRaspunsuri.Get("Blocat")
    Private Corect As String = ColRaspunsuri.Get("Corect")
    Private id As String = ColRaspunsuri.Get("id")
   
Next

You can also use THIS tool
 
Upvote 0

Ohanian

Active Member
Licensed User
Longtime User
Hi,

Try this :

B4X:
JSON.Initialize(intrebare.Replace("\", ""))
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…