仅在某些字段上使用自定义反序列化程序?

Fel*_*lix 5 gson

使用gson,是否可以仅在某些字段上使用自定义解串器/序列化器?的用户指南显示了如何注册一个适配器用于整个类型,而不是为特定字段.我想要这个的原因是因为我解析了自定义日期格式并将其存储在long成员字段中(作为Unix时间戳),因此我不想为所有Long字段注册类型适配器.

有没有办法做到这一点?

Jas*_*son 7

我还将日期值存储long在我的对象中,以便轻松防御副本.我还想要一种在序列化对象时只覆盖日期字段而不必写出进程中所有字段的方法.这是我提出的解决方案.不确定它是处理这个的最佳方式,但它似乎表现得很好.

该DateUtil班是这里使用一个自定义的类来获得一个Date解析的String.

public final class Person {
  private final String firstName;
  private final String lastName;
  private final long birthDate;

  private Person(String firstName, String lastName, Date birthDate) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDate = birthDate.getTime();
  }

  public static Person getInstance(String firstName, String lastName, Date birthDate) {
    return new Person(firstName, lastName, birthDate);
  }

  public String toJson() {
    return new GsonBuilder().registerTypeAdapter(Person.class, new PersonSerializer()).create().toJson(this);
  }

  public static class PersonSerializer implements JsonSerializer<Person> {
    @Override
    public JsonElement serialize(Person person, Type type, JsonSerializationContext context) {
      JsonElement personJson = new Gson().toJsonTree(person);
      personJson.getAsJsonObject().add("birthDate", new JsonPrimitive(DateUtil.getFormattedDate(new Date(policy.birthDate), DateFormat.USA_DATE)));
      return personJson;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当序列化类时,该birthDate字段将作为格式String而不是long值返回.