简体   繁体   中英

Gson deserialize current object with extended class

I'm new to java (Hum... No... I learned Java at school 10 years ago but never really used it since today).

I have an object class which corresponds to my json and was generated with the website http://www.jsonschema2pojo.org/ (simplified here) :

public class ServerDatasObject {
  private Integer error;
  private Boolean isOffline;
  public Integer getError() {
      return error;
  }
  public Boolean getIsOffline() {
      return isOffline;
  }
}

And another class used to access all object data (simplified too) :

public class ServerDatasHandler extends ServerDatasObject {
  public ServerDatasHandler(String json) {
    Gson gson = new Gson();
    // how to populate current object using : gson.fromJson(json, ServerDatasObject.class);
  }
}

The question is in the code: how to populate current object? I searched and found something about InstanceCreator :

final Foo existing;
InstanceCreator<Foo> creator = new InstanceCreator<Foo>() {
  public Foo createInstance(Type type) { return existing; }
}

Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, creator).create();
Foo value = gson.fromJson(jsonString, Foo.class);
// value should be same as existing

but I don't understand how to use it and if it is what I need.

The final goal is to

{
  ServerDatasHandler serverDatasHandler = new ServerDatasHandler (json);
  do something with serverDatasHandler.getError()
}

Thanks for your help

You can create a separate static method which creates your handler from json:

public static ServerDatasHandler fromJsonConfig(String json) {
  Gson gson = new Gson();
  ServerDatasHandler handler = gson.fromJson(json, ServerDatasHandler.class);
  return handler;
}

Of course you can also move this method to a factory.

I never used InstanceCreator inside constructor because parsing JSON is almost never a task for a constructor. Preferably it should be hidden inside framework or your own factories. Though, your example with InstanceCreator should also work if you will return ServerDatasHandler.this from the createInstance method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM