consuming JSON

Asked

Viewed 3,750 times

3

I’m having trouble getting a file from the internet by JSON.

I have some data on this link http://www.sinestandar.com.br/maker/categorias.txt and I want to take to use in my application, the link returns something like:

{
   "Categorias":[
      {
         "nome":"Black",
         descricao:"Cortes de cabelo estilo Black",
         "icone":"http://mundomulheres.com/fotos/2013/10/dois-tipos-de-cortes-cacheados.jpg"
      },
      {
         "nome":"Casamento",
         descricao:"Cortes de cabelo para casamento",
         "icone":"http://www.belasdicas.com/wp-content/uploads/2012/07/penteados-para-casamento.jpg"
      }
   ]
}

I tried to do so

class DownloadJsonAsyncTask extends AsyncTask<String, Void, List<Trend>> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(ConsumirJsonTwitterActivity.this, "Aguarde", "Baixando JSON, Por Favor Aguarde...");
    }

    @Override
    protected List<Trend> doInBackground(String... params) {
        String urlString = params[0];
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(urlString);
        try {
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                String json = toString(instream);
                instream.close();
                List<Trend> trends = getTrends(json);
                return trends;
            }
        } catch (Exception e) {
            Log.e("DEVMEDIA", "Falha ao acessar Web service", e);
        }
        return null;
    }

    private List<Trend> getTrends(String jsonString) {
        List<Trend> trends = new ArrayList<Trend>();
        try {
            JSONArray trendLists = new JSONArray(jsonString);
            JSONObject trendList = trendLists.getJSONObject(0);
            JSONArray trendsArray = trendList.getJSONArray("trends");
            JSONObject trend;
            for (int i = 0; i < trendsArray.length(); i++) {
                trend = new JSONObject(trendsArray.getString(i));
                Log.i("DEVMEDIA", "nome=" + trend.getString("name"));
                Trend objetoTrend = new Trend();
                objetoTrend.name = trend.getString("name");
                objetoTrend.descricao = trend.getString("descricao");
                objetoTrend.icone = trend.getString("icone");
                trends.add(objetoTrend);
            }
        } catch (JSONException e) {
            Log.e("DEVMEDIA", "Erro no parsing do JSON", e);
        }
        return trends;
    }

    @Override
    protected void onPostExecute(List<Trend> result) {
        super.onPostExecute(result);
        dialog.dismiss();
        if (result.size() > 0) {
            ArrayAdapter<Trend> adapter = new ArrayAdapter<Trend>(ConsumirJsonTwitterActivity.this, android.R.layout.simple_list_item_1, result);
            setListAdapter(adapter);
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(ConsumirJsonTwitterActivity.this).setTitle("Atenção").setMessage("Não foi possivel acessar essas informções...").setPositiveButton("OK", null);
            builder.create().show();
        }
    }

But you’re making this mistake:

12-16 15:33:47.229  14947-14955/json.exemplo.com.testejson E/DEVMEDIA﹕ Erro no parsing do JSON
org.json.JSONException: Value {"Categorias":[{"icone":"http:\/\/mundomulheres.com\/fotos\/2013\/10\/dois-tipos-de-cortes-cacheados.jpg","descricao":"Cortes de cabelo estilo Black","nome":"Black"},{"icone":"http:\/\/www.belasdicas.com\/wp-content\/uploads\/2012\/07\/penteados-para-casamento.jpg","descricao":"Cortes de cabelo para casamento","nome":"Casamento"}]} of type org.json.JSONObject cannot be converted to JSONArray
        at org.json.JSON.typeMismatch(JSON.java:107)
        at org.json.JSONArray.<init>(JSONArray.java:91)
        at org.json.JSONArray.<init>(JSONArray.java:103)
        at json.exemplo.com.testejson.ConsumirJsonTwitterActivity$DownloadJsonAsyncTask.getTrends(ConsumirJsonTwitterActivity.java:76)

strange that it seems that it is taking the most data ta giving error in time to pass to the JSONArray trendLists;

To help anyone with the same problem I’m putting as I solved

private List<Categoria> getTrends(String jsonString) {
        List<Categoria> categorias = new ArrayList<Categoria>();
        try {
            JSONObject trendLists = new JSONObject(jsonString);
            JSONArray jArray = trendLists.getJSONArray("Categorias");


            for(int i=0; i<jArray.length(); i++){
                Categoria categoria = new Categoria();
                JSONObject json_data = jArray.getJSONObject(i);
                categoria.nome=json_data.getString("nome");
                categoria.descricao=json_data.getString("descricao");
                categoria.icone=json_data.getString("icone");
                categorias.add(categoria);
            }

        } catch (JSONException e) {
            Log.e("DEVMEDIA", "Erro no parsing do JSON", e);
        }
        return categorias;
    }
  • 1

    JSONArray trendLists shouldn’t be a JSONObject?

  • @Lucasnunes you were faster than me +1

  • I was looking from a website, I don’t know anything I’m trying to learn :/ , to well lost

  • @Ilgnerdeoliveira I added an example too.

3 answers

8


The "level root" of your "json" uses { ie is a Object and not a Array, the correct is you use JSONObject instead of JSONArray.

See here you try to convert something like {...} in Array:

JSONArray trendLists = new JSONArray(jsonString);

The right thing in this case is to use it like this:

JSONObject trendLists = new JSONObject(jsonString);

Note:

To pick up the description separately from the name, you must pick up first Categorias using JSONObject.getJSONArray and then nome and descricao (without accent) using a loop and JSONObject.getString.

Take an example:

JSONObject trendLists = new JSONObject(jsonString);
JSONArray arr = trendLists.getJSONArray("Categorias");
for (int i = 0; i < arr.length(); i++)
{
    String nome = arr.getJSONObject(i).getString("nome");
    String desc = arr.getJSONObject(i).getString("descricao");
    System.out.print(nome);
    System.out.print(":");
    System.out.println(desc);
}

Note: In your code I noticed that you tried to capture name instead of nome, in this line objetoTrend.name = trend.getString("name");

  • I used Jsonobject trendLists = new Jsonobject(jsonString); Log. d("test",trendLists.getString("Categories"); ai I managed to print the whole category , but I can’t get the name, separate description. tried so , Jsonobject categories = trendLists.getJSONObject("Categories");

4

I noticed another problem when passing your jsonlint url (http://jsonlint.com/): The Description field is not formatted correctly; it should be in quotes.

Parse error on line 4:
...Black",            descricao: "Cortes d
----------------------^
Expecting 'STRING'
  • True. It must be "Description": "content..."

  • thanks I didn’t even realize it, I’ll change it right now

1

William’s answer solves his problem.
But, a suggestion: you could use the Volley to facilitate this part.

Would something like this:

// lista de requisições
RequestQueue queue = Volley.newRequestQueue(this);

// não seria melhor chamar de `categorias.json`?
String url = "http://www.sinestandar.com.br/maker/categorias.txt";

// depois, para pegar o arquivo json:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>()
    {
        @Override
        public void onResponse(JSONObject response)
        {
            // ocorreu como esperado:
            JSONArray trendLists = response.getJSONArray("Categorias");

            // continuação do seu código.
        }
    },
    new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            // deu algo errado
        }
    });

queue.add(request);
  • When you place Requestqueue Queue = Volley.newRequestQueue(this); you are asked to create a class

  • You have to download some classes. In the answer indicates where to download.

Browser other questions tagged

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