Gson: JsonObject conversion error for JsonArray (JsonPrivate can not be cast to com.google.gson.JsonArray)

1

I'm trying to convert a JSONObject item to an ArrayList and for this I created this function from an example I saw here in the forum:

public static ArrayList<Produto> converte(JSONObject jsonObject){
            ArrayList<ArrayList> array = new ArrayList<>();
            String stringJSON = jsonObject.toString();

            JsonParser jsonParser = new JsonParser();
            JsonObject jObject = (JsonObject) jsonParser.parse(stringJSON);
            JsonArray jAProdutos = jObject.getAsJsonArray("produtosFavoritos");
            ArrayList<Produto> arrayProdutos = gson.fromJson(jAProdutos,ArrayList.class);

            return arrayProdutos();
}

But you're giving the error:

  

java.lang.ClassCastException: com.google.gson.JsonPrimitive can not be   cast to com.google.gson.JsonArray

JSON:

{"produtosFavoritos":"[]",
"listas":"[]",
"estabelecimentosFavoritos":"[]",
"email":"teste",
"experiencia":0,
"nome":"teste",,
"senha":"teste",
"nivel":1}
    
asked by anonymous 05.11.2016 / 16:43

1 answer

1

The problem is that the format of your JSON is incorrect. When you have an array, it can not be within " . Your corrected JSON would look like this:

{
  "produtosFavoritos":[],
  "listas":[],
  "estabelecimentosFavoritos":[],
  "email":"teste",
  "experiencia":0,
  "nome":"teste",
  "senha":"teste",
  "nivel":1
}

Another problem that can cause error in this code is return. arrayProdutos is not a function, so it should not have () .

    
05.11.2016 / 18:03