gson如何序列化和反序列化lombok生成的继承pojo?

osh3o9ms  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(475)

如何将java继承与 lombokfinal (不可变数据类型)和 Gson ?

@ToString
@Getter
@EqualsAndHashCode(callSuper = false)
public abstract class AbstractContext {
  protected final String applicationUuid;
  protected final String userUuid;
  protected final String accountUuid;

  public AbstractContext(
      String applicationUuid, String userUuid, String accountUuid) {
    this.applicationUuid = applicationUuid;
    this.accountUuid = accountUuid;
    this.userUuid = userUuid;
  }
@ToString
@Getter
@EqualsAndHashCode(callSuper = true)
public class ChildContext extends AbstractContext {
  private final String foobar;

  public ChildContext(
      String applicationUuid, String userUuid, String accountUuid, String foobar) {
    super(applicationUuid, userUuid, accountUuid);
    this.foobar = foobar;
  }
}
Gson gson = new Gson();
ChildContext inputB =
        gson.fromJson(
            "{\"application_uuid\":\"deadbeef\",\"user_uuid\":\"aaabbb_4958\",\"foobar\":\"abc\"}",
            ChildContext.class);

但是,我得到的结果是其他父类字段为空

foobar=abc, application_uuid=null, user_uuid=null, account_uuid=null

我试着从 lombok ,但仍然是相同的结果

qvtsj1bj

qvtsj1bj1#

您忘记指定字段命名策略。

Gson gson = new GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .create();
ChildContext inputB =
        gson.fromJson(
            "{\"application_uuid\":\"deadbeef\",\"user_uuid\":\"aaabbb_4958\",\"foobar\":\"abc\"}",
            ChildContext.class);

相关问题