3

Im new in this and cant explain why it keeps giving me the same error, over and over again. I was trying to retrieve a list of string but it keeps showing the error below. Here are the classes. Any help please!!

This is my code:

super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    listView = (ListView) findViewById(R.id.listGiros);


    try {
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            new JsonTask().
                    execute(new URL("http://vps197363.ovh.net:8002/api/api/giros.json"));
        } else {
            Toast.makeText(this, "Error de conexión", Toast.LENGTH_LONG).show();
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

public class JsonTask extends AsyncTask<URL, Void, List<Giro>> {

    @Override
    protected List<Giro> doInBackground(URL... urls) {
        List<Giro> giros = null;

        try {

            con = (HttpURLConnection) urls[0].openConnection();
            con.setConnectTimeout(15000);
            con.setReadTimeout(10000);
            con.setDoInput(true);

            // Obtener el estado del recurso
            int statusCode = con.getResponseCode();

            if (statusCode != 200) {
                giros = new ArrayList<>();
                giros.add(new Giro("Error", null, null));

            } else {


                InputStream in = new BufferedInputStream(con.getInputStream());


                GsonGiroParser parser = new GsonGiroParser();

                giros = parser.leerFlujoJson(in);


            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            con.disconnect();
        }
        return giros;
    }

    @Override
    protected void onPostExecute(List<Giro> giros) {

        if (giros != null) {
            adaptador = new AdaptadorDeGiros(getBaseContext(), giros);
            listView.setAdapter(adaptador);
        } else {
            Toast.makeText(
                    getBaseContext(),
                    "Ocurrió un error de Parsing Json",
                    Toast.LENGTH_SHORT)
                    .show();
            System.out.println("ADAPTADOR" + adaptador);
            System.out.println("ADAPTADOR" +  getBaseContext());
        }

    }
}

public class GsonGiroParser {


public List<Giro> leerFlujoJson(InputStream in) throws IOException {

    Gson gson = new Gson();

    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));

    List<Giro> giros = new ArrayList<>();

    reader.beginArray();

    while (reader.hasNext()) {

        Giro giro = gson.fromJson(reader, Giro.class);
        giros.add(giro);
    }


    reader.endArray();
    reader.close();
    return giros;
}
}

public class JsonGiroParser {


public List<Giro> leerFlujoJson(InputStream in) throws IOException {

    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    try {

        return leerArrayGiros(reader);
    } finally {
        reader.close();
    }

}


public List<Giro> leerArrayGiros(JsonReader reader) throws IOException {

    ArrayList<Giro> giros = new ArrayList<>();

    reader.beginArray();
    while (reader.hasNext()) {

        giros.add(leerGiro(reader));
    }
    reader.endArray();
    return giros;
}

public Giro leerGiro(JsonReader reader) throws IOException {

    String id = null;
    String nombre = null;
    String descripcion = null;

    reader.beginObject();


    while (reader.hasNext()) {
        String name = reader.nextName();
        switch (name) {
            case "id":
                id = reader.nextString();

                break;
            case "nombre":
                nombre = reader.nextString();
                break;
            case "descripcion":
                descripcion = reader.nextString();
                break;
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();
    return new Giro(id, nombre, descripcion);
}

}

public class Giro {

private String id;
private String nombre;
private String descripcion;

public Giro(String id, String nombre, String descripcion) {
    this.id = id;
    this.descripcion = descripcion;
    this.nombre = nombre;
}

public String getId() {
    return id;
}

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

public String getNombre() {
    return nombre;
}

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

public String getDescripcion() {
    return descripcion;
}

public void setDescripcion(String descripcion) {
    this.descripcion = descripcion;
}
}

and my json:

{
   "content":[
      {
         "descripcion":"Giro para carnicer\u00edas",
         "nombre":"Carnicer\u00eda",
         "id":1
      },
      {
         "descripcion":"Giro para pescader\u00edas",
         "nombre":"Pescados",
         "id":2
      },
      {
         "descripcion":"Giro para fruter\u00edas\r\n",
         "nombre":"Frutas y verduras",
         "id":3
      },
      {
         "descripcion":"",
         "nombre":"Pollos",
         "id":13
      },
      {
         "descripcion":"",
         "nombre":"Abarrotes",
         "id":14
      },
      {
         "descripcion":"",
         "nombre":"Comida",
         "id":15
      },
      {
         "descripcion":"",
         "nombre":"Ex\u00f3ticos",
         "id":16
      },
      {
         "descripcion":"",
         "nombre":"Otros",
         "id":17
      }
   ]
}
4
  • just remove de content key, your json parser is specting an array to parse and doesnt understand the "content" key. Commented Oct 6, 2016 at 16:02
  • @melli-182 Thanks for answer me. how do I do that? Commented Oct 6, 2016 at 16:11
  • if you cant manipulate the json youre getting i suggest to follow Jaythaking's answer. You can create a Container Object that has the same structure of your json (with the content attribute thats an array of Giros) Commented Oct 6, 2016 at 17:40
  • 1
    @melli-182 thank you! it really help me! Commented Oct 13, 2016 at 14:40

1 Answer 1

1

You can just modify the POJO that you are using in order to handle that "content" field, then parse the inner Array:

-----------------------------------com.example.Content.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.Map;

public class Content {

private String descripcion;
private String nombre;
private Integer id;
/**
* 
* @return
* The descripcion
*/
public String getDescripcion() {
return descripcion;
}

/**
* 
* @param descripcion
* The descripcion
*/
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}

/**
* 
* @return
* The nombre
*/
public String getNombre() {
return nombre;
}

/**
* 
* @param nombre
* The nombre
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}

/**
* 
* @return
* The id
*/
public Integer getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}

}

-----------------------------------com.example.GiroContainer.java-----------------------------------

package com.example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GiroContainer {

private List<Content> content = new ArrayList<Content>();

/**
* 
* @return
* The content
*/
public List<Content> getContent() {
return content;
}

/**
* 
* @param content
* The content
*/
public void setContent(List<Content> content) {
this.content = content;
}


}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a million! Worked perpectly
You're welcome... An easy way to create your pojo is this website: jsonschema2pojo.org (It's convert your json to a pojo format accepted) be sure you select JSON instead of JSON Schema

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.