I am trying to parse Json string into Java object using Gson library but i encountered StackoverflowException.
java.lang.StackOverflowError
com.google.gson.internal.$Gson$Types.checkNotPrimitive($Gson$Types.java:431)
com.google.gson.internal.$Gson$Types.access$000($Gson$Types.java:42)
com.google.gson.internal.$Gson$Types$WildcardTypeImpl.($Gson$Types.java:540)
com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:108)
com.google.gson.internal.$Gson$Types$WildcardTypeImpl.($Gson$Types.java:549)
com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:108)
com.google.gson.internal.$Gson$Types$WildcardTypeImpl.($Gson$Types.java:542)
com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:108)
com.google.gson.internal.$Gson$Types$WildcardTypeImpl.($Gson$Types.java:549)
com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:108)
Json string:
{"password":"ac@123","role":"normaluser","name":"Archana Chatterjee","username":"a.chatterjee","designation":"Teacher","id":"T_02","age":42}
Parsing code:
Entity entity = null;
entity = gson.fromJson(json, Staff.class);
Java classes:
public class Staff extends LoginEntity {
Logger logger = Logger.getRootLogger();
@SerializedName("name")
String name;
@SerializedName("designation")
String designation;
@SerializedName("role")
String role;
@SerializedName("age")
int age;
}
public abstract class LoginEntity extends Entity {
private static final Logger logger = Logger.getRootLogger();
@SerializedName("username")
String mailid;
@SerializedName("password")
String password;
}
Root class for all.
public abstract class Entity {
Logger logger = Logger.getRootLogger();
@SerializedName("id")
public String id;
}
I also found out related error in Gson2.2.2, but i am using Gson 2.2.4 . So, just want to make sure Is this a error from my side or is it mentioned error in the link.
From the Gson User Guide:
If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
...
By default, if you mark a field as transient, it will be excluded. As well, if a field is marked as "static" then by default it will be excluded.
So the solution to your problem is simply to mark your logger
as transient or static, for example:
transient Logger logger = Logger.getRootLogger();
This way the variable will be excluded from serialization and deserialization, and you won't get that error.
UPDATE: Looks like Gson now supports a @Expose(serialize = boolean)
annotation to explicitly state what you want serialized and what you don't. However, for it to be respected you must call .excludeFieldsWithoutExposeAnnotation()
on your GsonBuilder and annotate every field that you want exposed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With