서버에서 수신 한 객체에 Joda DateTime
필드가 있습니다. 예를 들어 필드 값은 2016-09-01T11:30:00.000+03:00
입니다. 그런 다음 gson.toJson()
을 호출하면 필드가 날짜 전용 문자열 2016-09-01
으로 변환됩니다.Goda는 Joda DateTime 객체를 구문 분석 할 때 시간을 생략합니다.
코드 :
final GsonBuilder builder = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeSerializer());
final Gson gson = builder.create();
String str = gson.toJson(response.body());
내 사용자 정의 유형 어댑터의 serialize
메서드가 호출되지 않은 것으로 나타났습니다 디버깅. 어쩌면 나는 이것을 정확하게 이해하지 못하고 있지만, 객체를 JSON 문자열로 변환 할 때 (이 경우 deserialize
이 문자열에 gson.fromJson()
을 사용할 때 호출 됨) 사용되기를 기대하고있었습니다.
이 사용자 정의 유형의 어댑터입니다 :
public class DateTimeSerializer implements JsonDeserializer<DateTime>, JsonSerializer<DateTime>
{
private static final DateTimeFormatter DATE_FORMAT = ISODateTimeFormat.date();
@Override
public DateTime deserialize(final JsonElement je, final Type type, final JsonDeserializationContext jdc) throws JsonParseException {
final String dateAsString = je.getAsString();
return dateAsString.length() == 0 ? null : DATE_FORMAT.parseDateTime(dateAsString);
}
@Override
public JsonElement serialize(final DateTime src, final Type typeOfSrc,
final JsonSerializationContext context) {
return new JsonPrimitive(src == null ? "" : DATE_FORMAT.print(src));
}
}
가 이런 식으로 해석하는 이유 어떤 생각과 방법이이 문제를 해결하기 위해? 감사!
글쎄, 당신은 명시 적으로'ISODateTimeFormat.date()'를 사용하고 있습니다. * is *는 단지 날짜/시간보다는 날짜가 될 것입니다. 그래서 시간 정보를 잃어 버리는 것에 놀라지 않습니다. 틀림없이'serialize '를 호출하지 않으면 걱정이됩니다 ... –
바보 같은 저 ...'serialize' 부분을 조사하면서'dateTime()'대신'date()'를 사용하고 있음을 알지 못했습니다. 덕분에 문제가 해결되었습니다. –