Post

String dateFormat 변환 관련. Jackson Deserialize

@Pathvariable 형태의 파라미터등을 date type으로 받으려면 converter를 시켜줄 설정 및 class가 필요하다.

​

우선 @PathVariable 부분을 변경하는 부분은 아래와 같다.

​

Paramter를 받는 @Controller 클래스 안에 아래와 같이 선언한다.

@InitBinder
	public void initBind(WebDataBinder binder) {

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, "memoTsp", new CustomDateEditor(dateFormat, true));
	}

중요한 부분은 date type 형태는 yyyy.MM.dd 형태는 짤리니 사용하면 안되고 위와 같이 yyyy-mm-dd 나 기타 mmddYY등을 사용하면 정상적으로 되는 것 같다.

​

@RestController
public Class RestController {

@RequestMapping(value ="/test/{testDate}")
public String testContoller(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") Date testDate) {
      ~~~
 return "";
}


@InitBinder
	public void initBind(WebDataBinder binder) {

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, "testDate", new CustomDateEditor(dateFormat, true));
	}
}

이후 @RequestBody 받는 부분에서는 @JsonDeserialize(using = CustomJsonDateDeserializer.class) 애노테이션을 이용하여 testDate 변수 위에 걸어 둔다.

​

그렇게 하면 @RequestBody로 받을 때 데이터 알맞게 들어가지게 된다.

@RestController
public Class RestController {

@RequestMapping(value ="/test/{testDate}")
public String testContoller(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") Date testDate,
                                  @RequestBody TestModel testModel) {
      ~~~
 return "";
}


@InitBinder
	public void initBind(WebDataBinder binder) {

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, "testDate", new CustomDateEditor(dateFormat, true));
	}
}
@Date
public Class testModel {
 @JsonDeserialize(using = CustomJsonDateDeserializer.class)
 private testDate;
}
public class CustomJsonDateDeserializer extends JsonDeserializer {

	@Override
	public Date deserialize(JsonParser jsonParser, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date = jsonParser.getText();
		try {
			return format.parse(date);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

}

위와 같은 설정을 해줘야지 정상적으로 type에 맞게 작업이 가능하다.

​

Unix Time stamp 변환 Deserialize

kotlin version

class UnixTimestampDeserializer : JsonDeserializer() {
    @Throws(IOException::class)
    override fun deserialize(jsonParser: JsonParser, deserializationContext: DeserializationContext): LocalDateTime {
        val timestamp: Long = jsonParser.longValue
        return LocalDateTime.ofInstant(
            Instant.ofEpochMilli(timestamp),
            TimeZone.getDefault().toZoneId()
        )
    }
}
data class Model (
...
@JsonDeserialize(using = UnixTimestampDeserializer::class)
var createdAt: LocalDateTime,
...
)

​

This article is licensed under CC BY 4.0 by the author.