Gson Exception: No-args constructor for class XXX does not exit.

来源:互联网 发布:华为大数据产业园 编辑:程序博客网 时间:2024/05/14 22:03

Gson Exception: No-args constructor for class XXX does not exit.

|No TrackBacks
Use JDO and RESTful web services at GAE. Usually need to parser JSON format string by Gson. But, some JDO class doesn't have No-args constructor, public YourClass(){}, and therefore the gson instance will throw out exception, No-args constructor for class XXX does not exit.
There are two ways to fix this problem:
One, add No-args constructor in the JDO class.
The other is use InstanceCreator to instead a no-argument constructor.
Example:

public class YourClassInstanceCreator implements InstanceCreator<YourClass> {
 public YourClass createInstance(Type type) {
   return new YourClass(null, null, null, null);
 }
}

Then build the gson instance through GsonBuilder, like
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(YourClass.class, new YourClassInstanceCreator());
Gson gson = builder.create();
stoken = gson.fromJson(json, YourClass.class);
原创粉丝点击