开发者

Use a custom deserializer only on certain fields?

开发者 https://www.devze.com 2023-03-23 09:20 出处:网络
With gson, is it possible to use a custom deserializer / serializer only on certain fields? The user guide shows how to register an adapter for an entire type, not for specific fields. 开发者_开发技巧

With gson, is it possible to use a custom deserializer / serializer only on certain fields? The user guide shows how to register an adapter for an entire type, not for specific fields. 开发者_开发技巧The reason why I want this is because I parse a custom date format and store it in a long member field (as a Unix timestamp), so I don't want to register a type adapter for all Long fields.

Is there a way to do this?


I also store Date values as long in my objects for easy defensive copies. I also desired a way to override only the date fields when serializing my object and not having to write out all the fields in the process. This is the solution I came up with. Not sure it is the optimal way to handle this, but it seems to perform just fine.

The DateUtil class is a custom class used here to get a Date parsed as a 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;
    }
  }
}

When the class is serialized, the birthDate field is returned as a formatted String instead of the long value.


Don't store it as a long, use a custom type with a proper adapter. Inside your type, represent your data any way you want -- a long, why not.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号