Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a custom deserializer only on certain fields?

Tags:

gson

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?

like image 469
Felix Avatar asked Jul 27 '11 08:07

Felix


2 Answers

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.

like image 160
Jason Avatar answered Nov 09 '22 09:11

Jason


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.

like image 35
slezica Avatar answered Nov 09 '22 08:11

slezica