Gson Custom Adapters

Gson 라이브러리λ₯Ό μ΄μš©ν•˜μ—¬ getter/setter λ™μž‘μ΄ λΆˆκ°€ν• μ‹œμ— μ•„λž˜μ™€ 같이 μ–΄λŽν„°λ₯Ό κ΅¬μ„±ν•˜μ—¬ μ‚¬μš©ν•¨

static class SampleDto {
  private String date;

  public String getDate() {
      return date + "[ >>> GET ]";
  }

  public void setDate(String date) {
      this.date = date + "[ <<< SET ]";
  }
}
class SampleDtoAdapter extends TypeAdapter<SampleDto> {

  @Override
  public void write(JsonWriter out, SampleDto value) throws IOException {
      out.beginObject();
      out.name("date");
      out.value(value.getDate());
      out.endObject();
  }

  @Override
  public SampleDto read(JsonReader in) throws IOException {
      SampleDto sample = new SampleDto();
      in.beginObject();
      String fieldName = null;

      while (in.hasNext()) {
          JsonToken token = in.peek();

          if (token.equals(JsonToken.NAME)) {
              fieldName = in.nextName();
          }

          if (("date").equals(fieldName)) {
              token = in.peek();
              sample.setDate(in.nextString());
          }
      }

      in.endObject();
      return sample;
  }
}
public Gson getCustomBuilder() {
  GsonBuilder builder = new GsonBuilder();
  builder.registerTypeAdapter(SampleDto.class, new SampleDtoAdapter());
  builder.setPrettyPrinting();

  return builder.create();
}

public static void main() {
  Object[] data = Stream
      .iterate(
          new HashMap(),
          map -> {
              map.put("date", (new Date()).toString());
              return map;
          }
      )
      .limit(2)
      .toArray();

  Gson gson = getCustomBuilder();

  String strJson = new Gson().toJson(data[0]);

  SampleDto sample = gson.fromJson(strJson, (Type) SampleDto.class);

  System.out.println(sample.getDate());

}
Wed Jul 03 16:10:51 KST 2019[ <<< SET ][ >>> GET ]

DTO 객체가 λ°°μ—΄λ‘œ 듀어왓을 경우둜 μˆ˜μ •ν•΄λ³΄μž