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 κ°μ²΄κ° λ°°μ΄λ‘ λ€μ΄μμ κ²½μ°λ‘ μμ ν΄λ³΄μ
β Anti-Pattern