Consuming Json[Array & Object] on Android

Asked

Viewed 1,196 times

1

According to the comments from some users of this forum, I read some articles talking about more or less what I wanted to do.

  • Read article:

consuming JSON

From of this I I tried to create my own code, however I’m with serious problems, which are:

1) I don’t know how to "join" the Jsonrestfull class with the Shopping Class, so I can reuse the Json code for others classes.

2) Using the question (1), do not know how to take the data found in JSON and make a comparison. 3) I don’t know if the code is correct.

Jsonrestfull.java

package com.vuforia.samples.Books.app.Neoris;

import android.os.AsyncTask;
import android.util.Log;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by th on 30/06/17.
 */

public class JSONRestFull {

    // Define o URL do Servidor para obter os dados do Book
    private static final String LOGTAG = "Json";
    private String mServerJsonURL = "http://www.teste.com/shopping.json";
    private String mBookDataJSONFullUrl;

    // Indica se o aplicativo está atualmente carregando os dados do Book
    private boolean mIsLoadingBookData = false;

    // Dados do Shopping ativo
    private Shopping mShoppingData;


    /**
     * Obtém os dados do Book de um objeto JSON
     */

    private class GetBookDataTask extends AsyncTask<Void, Void, Void> {

        protected void onPreExecute() {
            mIsLoadingBookData = true;

            // Inicialize o url completo do BOOK atual para pesquisar
            // para os dados do JSON
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append(mServerJsonURL);

            mBookDataJSONFullUrl = sBuilder.toString();
        }


        protected Void doInBackground(Void... params) {
            HttpURLConnection connection = null;

            try {
                // Conecta ao Servidor para obter os dados do Book no JSON
                URL url = new URL(mBookDataJSONFullUrl);
                conectarServidorJson(url);

                int status = connection.getResponseCode();

                // Verifica se o URL do JSON existe e a conexão
                // foi bem sucedida
                if (status != HttpURLConnection.HTTP_OK) {
                    // Limpa as variáveis ​​de dados da Classe
                    mShoppingData = null;
                }

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                // Limpa qualquer referência antiga dos mData
                limpaReferenciaAntiga(mShoppingData);

                JSONObject jsonObject = new JSONObject(builder.toString());

                // Gera um novo objeto do JSON Shopping
                mShoppingData = new Shopping();
                geraNovoObjetoJson(jsonObject, mShoppingData);

            } catch (Exception e) {
                Log.d(LOGTAG, "Couldn't get Json's. e: " + e);
            } finally {
                connection.disconnect();
            }

            return null;
        }
    }

    public void setmServerJsonURL(String mServerJsonURL) {
        this.mServerJsonURL = mServerJsonURL;
    }

    private void conectarServidorJson(URL url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.connect();
    }

    private void limpaReferenciaAntiga (Shopping mShoppingData){
        if(mShoppingData != null){
            mShoppingData = null;
        }
    }

    private void geraNovoObjetoJson (JSONObject jsonObject, Shopping mShoppingData) throws JSONException {

        // Gera os Objetos Json do Shopping
        mShoppingData.setNome(jsonObject.getString("nome"));
        mShoppingData.setLicenseKey(jsonObject.getString("licenseKey"));
        mShoppingData.setAccessKey(jsonObject.getString("acessKey"));
        mShoppingData.setSecretKey(jsonObject.getString("secretKey"));
        mShoppingData.setLAT_1(jsonObject.getDouble("LAT_1"));
        mShoppingData.setLAT_2(jsonObject.getDouble("LAT_2"));
        mShoppingData.setLONG_1(jsonObject.getDouble("LONGI_1"));
        mShoppingData.setLONG_2(jsonObject.getDouble("LONGI_2"));
    }



}

Shopping.json

{
    "shoppingsObj": {
        "shoppings": [{
                "nome": "Bangu Shopping",
                "licenseKey": "Ad84Z0z/////AAAAGSgcOhPVvkoniWypHW2Dfsw+iX69si/",
                "acessKey": "f854427",
                "secretKey": "16208b",
                "LAT_1": ["-22.879832"],
                "LAT_2": ["-22.877738"],
                "LONGI_1:": ["-43.468601"],
                "LONGI_2:": ["-43.465978"]
            },
            {
                "nome": "Boulevard Shopping Campos",
                "licenseKey": "AULCxLD/////AAAAGa6JoRhAAk70lshljOUpGeN7XUgbJ/",
                "acessKey": "6ad29c",
                "secretKey": "370db",
                "LAT_1": ["-21.755484"],
                "LAT_2": ["-21.753139"],
                "LONGI_1:": ["-41.350870"],
                "LONGI_2:": ["-41.346417"]
            }
        ]
    }
}
  • Do you want to read the right Shopping.json file?! What is the problem with Jsonrestfull.java? You then want to use this data fetched from json in another class?!

  • Are you using parcelable or serializable?

  • @acklay , 1) I want to read shopping.json and use shoppingObj.lat and shopping.Long comparing and traversing all of its vectors, to check if the user is within the perimeter. If he is inside, he will walk through the mall.nome and shopping.Keys of this mall and will make the "set". 2) I don’t know if this Jsonrestfull code is correct. 3) I can’t tell you, I only read the topic I left in the question.

2 answers

2

When interpreting JSON, a piece of its structure was disregarded: the object shoppingsObj and the array malls contained within it. Latitudes and longitudes are also within an array.

It is also worth noting that your method geraNovoObjetoJson assumes that JSON will contain only one mall, when in fact it may contain several. Even in the JSON of your example there are two malls.

Another version of your method geraNovoObjetoJson would be:

private void geraNovoObjetoJson (JSONObject jsonObject, List<Shopping> mShoppingData) throws JSONException {
    JSONObject shoppingsObj = jsonObject.getJSONObject("shoppingsObj");
    JSONArray shoppingsJson = shoppingsObj.getJSONArray("shoppings");
    for (int i = 0; i < shoppingsJson.length(); i++) {
      JSONObject shoppingJson = shoppingsJson.getJSONObject(i);
      // Gera os Objetos Json do Shopping
      Shopping shopping = new Shopping();
      shopping.setNome(shoppingJson.getString("nome"));
      shopping.setLicenseKey(shoppingJson.getString("licenseKey"));
      shopping.setAccessKey(shoppingJson.getString("acessKey"));
      shopping.setLat1(shoppingJson.getJSONArray("LAT_1").getDouble(0));
      shopping.setLat2(shoppingJson.getJSONArray("LAT_2").getDouble(0));
      shopping.setLon1(shoppingJson.getJSONArray("LONGI_1").getDouble(0));
      shopping.setLon1(shoppingJson.getJSONArray("LONGI_2").getDouble(0));
      mShoppingData.add(shopping);
    }
  }

Notice that I changed the type of the variable mShoppingData of Shopping for List<Shopping>. This version of the method also considers that there will always be at least 1 object inside the arrays LAT_1, LAT_2, LONGI_1 and LONGI_2.


Interpreting JSON manually the way you are doing may become costly in the long run.

During studies or in small projects there are no big problems. For larger projects I recommend using libraries such as Gson or Jackson or , which convert Pojos to JSON and vice versa.

0


I considered @Leonardo Lima’s reply But I changed the code and used the Volley

For those who want to learn to do the same as me, I used the following:

package com.vuforia.samples.Books.ui.ActivityList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.vuforia.samples.Books.R;
import com.vuforia.samples.Books.app.Neoris.GPSTracker;
import com.vuforia.samples.Books.app.Neoris.Shopping;
import com.vuforia.samples.Books.app.Neoris.VolleyAppController;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by th on 05/07/17.
 */

public class ShoppingsJsonScreen extends Activity {

    // json array response url
    private String urlJsonArry = "http://jsonvu.esy.es/shoppings.json";

    private static String TAG = ShoppingsJsonScreen.class.getSimpleName();
    private Button btnMakeObjectRequest, btnMakeArrayRequest;

    // Progress dialog
    private ProgressDialog pDialog;

    private TextView txtResponse;

    // temporary string to show the parsed response
    private String jsonResponse;


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

        btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
        txtResponse = (TextView) findViewById(R.id.txtResponse);

        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Carregando Json...");
        pDialog.setCancelable(false);

        btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // making json array request
                makeJsonArrayRequest();
            }
        });

    }

    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    /**
     * Method to make json array request where response starts with [
     * */
    private void makeJsonArrayRequest() {

        showpDialog();

        JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                        try {
                            // Parsing json array response
                            // loop through each json object
                            jsonResponse = "";
                            for (int i = 0; i < response.length(); i++) {

                                JSONObject shoppingObj = (JSONObject) response.get(i);
                                JSONObject shoppingInfoObj = shoppingObj.getJSONObject("informacoes");

                                Double shoppingLAT_1 = shoppingObj.getDouble("LAT_1");
                                Double shoppingLAT_2 = shoppingObj.getDouble("LAT_2");
                                Double shoppingLONG_1 = shoppingObj.getDouble("LONG_1");
                                Double shoppingLONG_2 = shoppingObj.getDouble("LONG_2");

                                String shoppingNome = shoppingInfoObj.getString("nome");
                                String shoppingLicenseKey = shoppingInfoObj.getString("licenseKey");
                                String shoppingAccessKey = shoppingInfoObj.getString("accessKey");
                                String shoppingSecretKey = shoppingInfoObj.getString("secretKey");


                                // Cria o Class Object
                                GPSTracker gps;
                                Shopping shop;
                                gps = new GPSTracker(ShoppingsJsonScreen.this);
                                shop = new Shopping(ShoppingsJsonScreen.this);

                                if((gps.getLatitude() >= shoppingLAT_1 && gps.getLatitude() <= shoppingLAT_2)
                                        && (gps.getLongitude() >= shoppingLONG_1 && gps.getLongitude() <= shoppingLONG_2)){
                                    jsonResponse += "LAT_1: " + shoppingLAT_1 + "\n\n";
                                    jsonResponse += "LAT_2: " + shoppingLAT_2 + "\n\n";
                                    jsonResponse += "LONG_1: " + shoppingLONG_1 + "\n\n";
                                    jsonResponse += "LONG_2: " + shoppingLONG_2 + "\n\n";

                                    jsonResponse += "Nome: " + shoppingNome + "\n\n";
                                    jsonResponse += "LicenseKey: " + shoppingLicenseKey + "\n\n";
                                    jsonResponse += "AccessKey: " + shoppingAccessKey + "\n\n";
                                    jsonResponse += "SecretKey: " + shoppingSecretKey + "\n\n";

                                    // Adiciona as Informações Obtidas do determinado Shopping
                                    shop.setShoppingNome(shoppingNome);
                                    shop.setShoppingLicenseKey(shoppingLicenseKey);
                                    shop.setShoppingAccessKey(shoppingAccessKey);
                                    shop.setShoppingSecretKey(shoppingSecretKey);


                                }
                            }

                            txtResponse.setText(jsonResponse);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Erro: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }

                        hidepDialog();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Erro: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                hidepDialog();
            }
        });

        // Adding request to request queue
        VolleyAppController.getInstance().addToRequestQueue(req);
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.