Deserialize JSON from MongoDB on Android

0

I am relatively new in the mobile development I was working with Mongo consuming an API that local but now I want to know how to deserialize the JSON data that I consume from the API.

Here is how I am working (Localhost), I have managed to show it to me as a String but I would like to serialize it to work it better.

If someone could guide me on how to do it, thank you in advance and a greeting!

public class MainActivity extends AppCompatActivity {

    private TextView mResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mResult = (TextView) findViewById(R.id.tv_result);

        //hacer solicitud GET
        new GetDataTask().execute("http://[IP]:3000/api/product/5c2ae8c084f3ef3ffc369157");
    }

    class GetDataTask extends AsyncTask<String, Void, String> {

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {

            super.onPreExecute();

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Loading data...");
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                return getData(params[0]);
            } catch (IOException ex) {
                return "Network error !";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            //configurar la respuesta de datos a textView
            mResult.setText("\n"+result);

            //cancelar el diálogo de progreso
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }

        private String getData(String urlPath) throws IOException {
            StringBuilder result = new StringBuilder();
            BufferedReader bufferedReader =null;

            try {
                //Inicializar y configurar la solicitud, luego conectarse al servidor
                URL url = new URL(urlPath);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setReadTimeout(10000 /* milliseconds */);
                urlConnection.setConnectTimeout(10000 /* milliseconds */);
                urlConnection.setRequestMethod("GET");
                urlConnection.setRequestProperty("Content-Type", "application/json"); //Establecer encabezado
                urlConnection.connect();

                //Leer la respuesta de datos del servidor
                InputStream inputStream = urlConnection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }


            } finally {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            }

            return result.toString();
        }

    }

This is how I managed to show me the JSON:

That's why I want to learn how to deserialize it.

    
asked by Irving Gonzalez 02.01.2019 в 04:06
source

2 answers

0

Welcome. I imagine that what you would like is to have an Array loaded with the data that comes to you in the json.

To help us parse the best is to convert the string into a JSONObject and JSONArray as appropriate and then go through them to extract the data.

Here is a small example of how it could be:

private Array<Product> parseProducts(String result){
   Array<Product> products = new Array()
   //Primero instanciamos un objeto json con el String que ya conseguiste:
   JSONObject json = new JSONObject(result);

   //Leemos el campo products que contiene el Array de productos.
   JSONArray jProducts = json.getJSONArray("products")

   for (JSONObject jProduct : json){ //Recorro el array para parsear cada producto

      Product product = new Product();//Crea tu propio modelo Producto para que contenga los datos que vallas a necesitar

      try{
         product.id = jProduct.getString("_id");//Asi consigo finalmente los campos del json
         product.name = jProduct.getString("name");
         product.price = jProduct.getDouble("price");
         //Continuar con los demas campos...

      }catch (JSONException e) {
         e.printStackTrace();
      }
      array.add(product)
   }
   return products;
}
    
answered by 02.01.2019 / 16:30
source
0

You can modify this method and apply it to your json structure:

Class to store the data structure:

public class Event {

/** Titulo */
public final String titulo;

/** Numero de personas que sintio el terremoto */
public final String numeroPersonas;

/** sensasion */
public final String intensidad;


public Event(String titulo, String numeroPersonas, String intensidad) {
    this.titulo = titulo;
    this.numeroPersonas = numeroPersonas;
    this.intensidad = intensidad;
}
}

application of the class

private static Event extraccionCaracteristicasDelJson(String terremotosJSON) {
    // en caso de que este vacio el json
    if (TextUtils.isEmpty(terremotosJSON)) {
        return null;
    }

    try {
        JSONObject baseJson = new JSONObject(terremotosJSON);
        JSONArray caracteristicasArray = baseJson.getJSONArray("items");

        // si existe algun resultado
        if (caracteristicasArray.length() > 0) {
            // Se extrae el primer elemento de interes
            JSONObject elemento = caracteristicasArray.getJSONObject(0);
            JSONObject propiedades = elemento.getJSONObject("properties");

            // Extract out the title, number of people, and perceived strength values
            String titulo = propiedades.getString("title");
            String numeroPersonas = propiedades.getString("felt");
            String intensidad = propiedades.getString("cdi");

            // se llena y retorna una clase con la estructura de interés
            return new Event(titulo, numeroPersonas, intensidad);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Problema con el resultado json", e);
    }
    return null;
}
    
answered by 02.01.2019 в 19:35