Gson: Jsonobject to Jsonarray conversion error (Jsonprimitive cannot be cast to com.google.gson.Jsonarray)

Asked

Viewed 683 times

1

I am trying to convert a Jsonobject item into an Arraylist and for that 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 making a mistake:

java.lang.Classcastexception: com.google.gson.Jsonprimitive cannot be cast to com.google.gson.Jsonarray

JSON:

{"produtosFavoritos":"[]",
"listas":"[]",
"estabelecimentosFavoritos":"[]",
"email":"teste",
"experiencia":0,
"nome":"teste",,
"senha":"teste",
"nivel":1}
  • You can put the json you are parsed?

  • I added in the question

  • So the problem is that your arrays are quotation marks

1 answer

1


The problem is that the format of your JSON is incorrect. When you have an array, it cannot be inside ". 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 the return. arrayProdutosis not a function, so should not have ().

  • But how do I create json that way? When I place favorite products, for example, I do jsonUsuario.put("productsFavoritos", usuario.getProductsFavoritos()); and it already generates so automatically

  • 1

    Oh it worked out! i cast a cast for Jsonarray when it comes to adding to JSON: jsonUsuario.put("productsFavorites", usuario.getProductsFavorites(); Thank you very much!

Browser other questions tagged

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