programing

잭슨을 사용하여 JS 날짜를 역직렬화하려면 어떻게 해야 하나요?

newnotes 2023. 3. 16. 21:48
반응형

잭슨을 사용하여 JS 날짜를 역직렬화하려면 어떻게 해야 하나요?

다음 형식의 날짜 문자열을 ExtJs에서 가져옵니다.

'2011-04-08T09:00:00'

이 날짜를 역직렬화하려고 하면 시간대가 인도 표준시로 변경됩니다(시간 +5:30을 추가합니다).날짜를 역직렬화하는 방법은 다음과 같습니다.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);

이렇게 해도 시간대는 변경되지 않습니다.IST에서 아직 날짜를 알 수 있습니다.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat);

Timezone의 번거로움 없이 오는 날짜를 어떻게 역직렬화합니까?

작업을 찾았는데 프로젝트 내내 각 날짜 설정자에 주석을 달아야 합니다.Object Mapper를 작성할 때 형식을 지정할 수 있는 방법이 있습니까?

제가 한 일은 다음과 같습니다.

public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
    @Override
    public Date deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String date = jsonParser.getText();
        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

}

각 날짜 필드의 설정자 메서드에 다음과 같은 주석을 달았습니다.

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

이것으로 충분합니다.잭슨 2.0.4를 사용하고 있습니다.

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);

이 토픽에 관한 좋은 블로그가 있습니다.http://www.baeldung.com/jackson-serialize-dates Use @JsonFormat이 가장 간단한 방법입니다.

public class Event {
    public String name;

    @JsonFormat
      (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    public Date eventDate;
}

Varun Achar의 답변에 덧붙여, 이것은 java.time을 사용하는 Java 8 바리안트입니다.오래된 java.util 대신 LocalDate 및 ZonedDateTime을 지정합니다.날짜 클래스

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

    @Override
    public LocalDate deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException {

        String string = jsonparser.getText();

        if(string.length() > 20) {
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(string);
            return zonedDateTime.toLocalDate();
        }

        return LocalDate.parse(string);
    }
  }

@JsonFormat은 사용 중인 잭슨 버전에서 지원되는 표준 형식에서만 작동합니다.

예: 모든 표준 양식("yyy-MM-dd'T")과 호환됩니다.HH:mm:ss.SSZ", "yyy-MM-dd'T"잭슨 2.8.6의 경우 HH:mm:ss.SSS'Z', "EEE, dd MM yyy HH:mm:ss zz", "yyy-MM-dd")

언급URL : https://stackoverflow.com/questions/5591967/how-to-deserialize-js-date-using-jackson

반응형