Android Question Help migrate code to b4a

bollanog

Member
Hello, I would like how I can migrate a fraction of a code that I have from Android Studio to B4A, which I cannot find the solution and it is the only one I need. I attach the code that I have to migrate.

Java:
JSONObject respObj = new JSONObject(response);
JSONArray departamentos = new JSONArray(respObj.getString("departamentos"));

for (int i = 0; i < departamentos.length(); i++) {
       JSONObject row = departamentos.getJSONObject(i);
       arrayList.add(row.getString("nombre"));
}

input json

JSON:
{"departamentos":[{"id":"1","nombre":"CONCEJO MUNICIPAL"},{"id":"2","nombre":"CONSULTOR\u00cdA JUR\u00cdDICA"}],"servicios":[{"id":"1","tipo":"ASESOR\u00cdA \/ SOPORTE T\u00c9CNICO"},{"id":"2","tipo":"BASE DE DATOS"},{"id":"4","tipo":"COMPUTADORA"},{"id":"3","tipo":"IMPRESORA"},{"id":"5","tipo":"RED"}],"totales":"93"}

I have tried to do something similar but it didn't work.

B4X:
        Try
            Dim JSON As JSONParser
            JSON.Initialize(respuesta.GetString)
            Dim datos As Map = JSON.NextObject
            
            txtCountReporte.Text = datos.Get("totales")
            
            Dim JSON1 As JSONParser
            JSON1.Initialize(datos.Get("departamentos"))
            Dim departamentos As List = JSON1.NextArray
            For Each coljRoot As Map In departamentos
                Dim nombre As String = coljRoot.Get("nombre")
                Log(nombre)
            Next

'            JSON2.Initialize(datos.Get("servicios"))
            
        Catch
            Msgbox2Async("Error al procesar", "Aviso", "Aceptar", "", "", Null, False)
        End Try

Thanks for your help.
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Sub AppStart (Args() As String)
    Dim s As String = $"{"departamentos":[{"id":"1","nombre":"CONCEJO MUNICIPAL"},{"id":"2","nombre":"CONSULTOR\u00cdA JUR\u00cdDICA"}],"servicios":[{"id":"1","tipo":"ASESOR\u00cdA \/ SOPORTE T\u00c9CNICO"},{"id":"2","tipo":"BASE DE DATOS"},{"id":"4","tipo":"COMPUTADORA"},{"id":"3","tipo":"IMPRESORA"},{"id":"5","tipo":"RED"}],"totales":"93"}"$
    Dim root As Map = s.As(JSON).ToMap
    Dim departamentos As List = root.Get("departamentos")
    Dim res As List
    res.Initialize
    For Each m As Map In departamentos
        res.Add(m.Get("nombre"))
    Next
    Log(res)
End Sub
 
Upvote 1

bollanog

Member
Thanks, for the help I was almost close, my mistake was that I was not placing the List type variable as I did, and that I was defining another json. Thanks for the help.
 
Upvote 0
Top