A. Cati Ferreira
A. Cati Ferreira

Reputation: 33

Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $ GSON

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
      }
   ]
}

Upvotes: 3

Views: 1736

Answers (1)

Jaythaking
Jaythaking

Reputation: 2102

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;
}


}

Upvotes: 1

Related Questions