consuming JSON

3

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

I have some data in this link link and I want to get it 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 giving this error:

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 looks like it's getting the data over, giving it an error when it's time to move to JSONArray trendLists;

To Help anyone with the same problem I am putting as resolved

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;
    }
    
asked by anonymous 16.12.2014 / 18:42

3 answers

8

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

Here you try to convert something like {...} to Array :

JSONArray trendLists = new JSONArray(jsonString);

The right one in this case is to use this:

JSONObject trendLists = new JSONObject(jsonString);

Note:

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

See 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");

    
16.12.2014 / 18:55
4

I noticed another problem passing your url to jsonlint ( link ): The description field is not formatted correctly; it should be enclosed in quotation marks.

Parse error on line 4:
...Black",            descricao: "Cortes d
----------------------^
Expecting 'STRING'
    
16.12.2014 / 19:22
1

Guilherme's answer solves your problem.
But, one suggestion: you could use volley to make that part easier.

It would look 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);
    
16.12.2014 / 19:10