Dimmy Magalhães
Dimmy Magalhães

Reputation: 357

Gson.fromJson() throws StackOverflowError

We have this Json:

{
    "id": 500,
    "field1": "TESTE",
    "banco": {
        "id": 300,
        "descricao": "BANCO_TESTE"
    },
    "categorias": [
        {
            "id": 300,
            "descricao": "PT",
            "publica": true
        }
    ]
}

And my beans:

public class Asking implements Serializable {
     private long id;
     private String field1;
     private Bank bank;
     private List<Categoria> categorias;

     //[getters and setters]
}

The beans Bank and Categoria:

public class Bank implements Serializable {
private Long code;
private Long id;
private String descricao;
//getters and setters
}

public class Categoria implements Serializable {
private Long code;
private Long id;
private String descricao;
private boolean marcada;
private boolean publica;
//getters and setters
}

When I call:

gson.fromJson(strJson, tokenType);

The error appears:

Method threw 'java.lang.StackOverflowError' exception.

What is wrong?

Upvotes: 0

Views: 2414

Answers (1)

durron597
durron597

Reputation: 32323

I can't reproduce this problem. One of two things are wrong here:

  1. Your beans are not defined as you say they are. Check to see if they have other fields hidden within the getter and setter method section. This can happen if you have a circular reference.
    • You've stated in the comments that this is likely to be your problem. I recommend:
      1. Remove the extra fields from your bean
      2. Create a new class that contains the extra fields, and a field for the Asking instance
      3. Deserialize the Asking instance using Gson, and then pass it into the new class's constructor.
  2. You are doing something unexpected with your setup of the gson.fromJson method. Here's what I'm using that works great:

    public static void parseJSON(String jsonString) {
      Gson gsonParser = new Gson();
      Type collectionType = new TypeToken<Asking>(){}.getType();
      Asking gsonResponse = gsonParser.fromJson(jsonString, collectionType);
      System.out.println(gsonResponse);
    }
    

Either check your bean class definitions for extra fields, or, failing that, try to make your deserialization match mine.

Upvotes: 1

Related Questions