728x90
[문제]
Spring Framework에서 JSON으로 POST 방식으로 보낼 때 아래와 같은 에러가 발생했다.
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document
: Unexpected character ('l' (code 108)): was expecting double-quote to start field name
[원인]
JSON 형식이 문제가 됐다. Map을. toString() 한 결과 따옴표가 없는 결과가 출력된다. JSON 포맷은 모든 변수명에 큰따옴표가 붙어야 하고(doble-quote), 숫자나 boolean은 따옴표를 붙지 않는 규칙이 있다.
map.toString()
(java.lang.String) {startDate=20240322111640005, type=user, locale=EN, endDate=20240322111645005}
[해결 방법]
JSON 관련 에러가 발생했을 때, 아래와 같이 단계별로 확인해 보자.
1. JSON 형식 확인
위에서 얘기했던 것처럼 따옴표가 붙게 수정해줘야 한다. Java의 경우 ObjectMapper을 사용해 JSON 형식으로 변환해 주면 된다.
//Java
import com.fasterxml.jackson.databind.ObjectMapper;
...
ObjectMapper mapper = new ObjectMapper();
String strM = mapper.writeValueAsString(m);
ObjectMapper를 적용하면 아래와 같이 변경된다.
strM
(java.lang.String) {"number":13, "startDate":"20240322111640005","locale":"EN","endDate":"20240322111645005"}
2. HTTP 요청 헤더 확인
'Content-Type' 헤더가 'application/json'으로 설정되어 있는지 확인한다.
String sampleURL = "http://localhost:8080/sample";
URI uri = new URI(sampleURL);
URL url = uri.toURL();
// HttpURLConnection 객체를 생성해 openConnection 메소드로 url 연결
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
// application/json 형식으로 전송, Request body를 JSON으로 던져줌
conn.setRequestProperty("Content-Type", "application/json");
3. Escape 문자 확인
문자열 내에 따옴표나 역슬래시 같은 특수 문자가 있는 경우 escape 처리가 되어있는지 확인한다.
{
"message": "This is a \"quoted\" message"
}
[참고]
OKKY - REST API 관련 POST 테스트 중 JSON 문제? 도움 부탁드립니다.
안녕하세요 점심 식사는 맛있게들 하셨나요?현재 REST API의 각 Endpoint들을 junit을 사용하여 테스트 중에 있습니다. 아직 신입이라 테스트에 관해 부족한 점이 너무나도 많습니다..http request method
okky.kr
'개발 > 1일1문제해결' 카테고리의 다른 글
[Network] 내부IP와 외부IP는 왜 따로 있을까? (0) | 2024.05.14 |
---|---|
[Spring] try-catch에서 @Transactional이 안되는 이유 및 해결 (0) | 2024.04.09 |
[Tomcat] http로 redirect 되는 문제 (X-Forwarded 헤더) (0) | 2024.03.24 |
[Spring] @Autowired Nullpointexception 오류 해결 (+ Spring Security) (0) | 2024.03.21 |
[Apache] 413 Request Entity Too Large 오류 해결 (0) | 2024.03.07 |