Use a custom deserializer only on certain fields?

喜夏-厌秋 提交于 2019-12-12 09:39:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6841645/use-a-custom-deserializer-only-on-certain-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!