Transform a JSONArray into an ArrayObject

1

My problem is the following, I bring a json from my api , the same I pass it to a JSONArray the topic this is that I want to arm a Array<Especialidad> and I do not know how to do it.

Specialty_connect

public class Especialidad_connect extends AsyncTask<String, Void, String> {


    public String url = "http://192.168.1.55:8080/especialidad/";
    public JSONArray jArray;


    @Override
    protected String doInBackground(String... strings) {
        try {
            getJSON(url);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    public JSONArray getJSON(String url) throws IOException, JSONException {
        InputStream is = null;
        String result = "";


        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();

        jArray = new JSONArray(result);
        return jArray;
    }

I want to take this

To this

Where the json that I bring from my api is [{"idEspecialidad":"1","nombre":"clinico"},{"idEspecialidad":"2","nombre":"pediatra"}]

Specialty

public class Especialidad {
    long id;
    String nombre;

    public Especialidad(long idEspecialidad, String nombre) {
        this.id = idEspecialidad;
        this.nombre = nombre;
    }

    public Especialidad() {

    }


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

}
    
asked by Germanccho 09.02.2018 в 23:18
source

3 answers

2

By having your JSONArray you can obtain the values by means of a loop and add them to an instance of Especialidad and each instance to a specialty list.

Create a list:

 List<Especialidad> listadoEspecialidades = new ArrayList<Especialidad>();

and get the values of each JSONObject in the JSONArray and add them to an object and then to the list:

for (int i=0; i < jArray.length(); i++) {
    especialidad = new Especialidad();
    especialidad.setId(jArray.getJSONObject(i).getInt("idEspecialidad"));
    especialidad.setNombre(jArray.getJSONObject(i).getString("nombre"));
    listadoEspecialidades.add(especialidad);
}

This would be the code:

 jArray = getJSON(url);

 List<Especialidad> listadoEspecialidades = new ArrayList<Especialidad>();
                Especialidad especialidad;

 for (int i=0; i < jArray.length(); i++) {
     especialidad = new Especialidad();
     especialidad.setId(jArray.getJSONObject(i).getInt("idEspecialidad"));
     especialidad.setNombre(jArray.getJSONObject(i).getString("nombre"));
     listadoEspecialidades.add(especialidad);
 }

Important : Remember that the "Apache" classes for connection are obsolete on Android, you should use HttpUrlConnection :

 public JSONArray getJSON(String url) throws IOException, JSONException {
        InputStream is = null;
        String result = "";


        /*HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();*/

            try {
                URL urlConn = new URL(url);
                HttpURLConnection urlConnection = (HttpURLConnection) urlConn.openConnection();
                is = urlConnection.getInputStream();
                urlConnection.disconnect();
            }
            catch (MalformedURLException ex) {
                Log.e("Error !", ex.getMessage());
            }





        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();

        jArray = new JSONArray(result);
        return jArray;
    }
    
answered by 09.02.2018 / 23:52
source
1

First change the subject of the class AsyncTask modifying the third type of generic data to ArrayList<Especialidad> :

public class Especialidad_connect extends AsyncTask<String, Void, ArrayList<Especialidad>> {

This also modifies the subject of the method doInBackground to the following:

  protected ArrayList<Especialidad> doInBackground(String... strings) {

This to return the array of specialties from the method doInBackground .

Now to convert the JSONArray returned by the method getJSON() , you just have to go through it using a for :

@Override
protected ArrayList<Especialidad> doInBackground(String... strings) {
    try {
        JSONArray jArray = getJSON(url);

        ArrayList<Especialidad> especialdades = new ArrayList<Especialidad>();


        for(int i = 0, total = jArray.length();i<total;i++)
        {
        // obtenemos el JSONObject del indice i
          JSONObject especialidadJSON = jArray.getJSONObject(i); 
          Especialidad especialidad = new Especialidad();

          // le asignamos los valores del json a la especialidad
          especialidad.setId(especialidadJSON.getInt("idEspecialidad"));
          especialidad.setNombre(especialidadJSON.getString("nombre");

          // lo agregamos la coleccion
          especialdades.add(especialdiad);
        }

        return especialdades;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

Note how the getJSONObject method is used on JSONArray , this can get the json object of the specified index and access its properties.

This would be the complete code:

public class Especialidad_connect extends AsyncTask<String, Void, ArrayList<Especialidad>> {

    public String url = "http://192.168.1.55:8080/especialidad/";
    public JSONArray jArray;


    @Override
    protected ArrayList<Especialidad> doInBackground(String... strings) {
        try {
            JSONArray jArray = getJSON(url);

            ArrayList<Especialidad> especialdades = new ArrayList<Especialidad>();


            for(int i = 0, total = jArray.length();i<total;i++)
            {
            // obtenemos el JSONObject del indice i
              JSONObject especialidadJSON = jArray.getJSONObject(i); 
              Especialidad especialidad = new Especialidad();

              // le asignamos los valores del json a la especialidad
              especialidad.setId(especialidadJSON.getInt("id"));
              especialidad.setNombre(especialidadJSON.getString("nombre");

              // lo agregamos la coleccion
              especialdades.add(especialdiad);
            }

            return especialdades;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    public JSONArray getJSON(String url) throws IOException, JSONException {
        InputStream is = null;
        String result = "";


        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();

        jArray = new JSONArray(result);
        return jArray;
    }

    @Override
    public void onPostExecuted(ArrayList<Especialidad> especialidades)
    {
        // aqui manejas las especialidades retornadas
    }
}
    
answered by 10.02.2018 в 00:34
1

Another shorter way using the Jackson library would be:

String jsonString = "....";
ObjectMapper mapper = new ObjectMapper();
Especialidad[] arr = mapper.readValue(jsonString, Especialidad[].class);

link

    
answered by 10.02.2018 в 02:00