์ด๋ค ์ํฉ์ธ์ง...
์ธ๋ถ API๋ฅผ ํธ์ถํ๊ณ ์๋ต ๊ฐ์ ๋ฐ์ ๋ ๋ฐ์ํ ๋ฌธ์ ์ด๋ค.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.core.codec.DecodingException: JSON decoding error: Unexpected character (''' (code 39)): was expecting double-quote to start field name] with root cause
ํด์ํด๋ณด๋ฉด ์๋ต ๊ฒฐ๊ณผ๊ฐ single quotes์ด๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด๋ก ํ์ฑํ์ง ๋ชปํ๋ค๋ ๊ฒ ๊ฐ๋ค.
์ฐธ๊ณ ๋ก ๋ด๊ฐ ์์ฑํ ์ฝ๋๋ ์์ ๊ฐ๋ค.
ResponseDto ๊ฐ์ฒด๋ก ํ์ฑํ๋ ค๊ณ ํ์ง๋ง ์ ๋๋ก ๋์ง ์์๋ค.
JsonParser.Feature.ALLOW_SINGLE_QUOTES
์๋ต๊ฒฐ๊ณผ๋ฅผ ๊ฐ์ฒด๋ก ๋ฐ์ง ์๊ณ , String์ผ๋ก ๋จผ์ ๋ฐ์๋ค๊ฐ ObjectMapper๋ฅผ ์ด์ฉํด์ single quotes๋ก ํ์ฑํ๋ ๋ฐฉ๋ฒ์ ํ์ฉํด๋ดค๋ค.
ํด๋น ํด๊ฒฐ๋ฐฉ๋ฒ์ ๋คํํ baeldung์ ์ ๋์์์๋ค.
์ฝ๋ ๊ตฌํ
@RequiredArgsConstructor
@Service
@Slf4j
public class WebClientService {
@Value("${alan.key}")
private String alanId;
private final WebClient webClient = WebClient.builder().build();
private final ObjectMapper objectMapper = new ObjectMapper().configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
public Flux<AlanResponseDto> getResponse(){
return webClient.get()
.uri("https://kdt-api-function.azurewebsites.net/api/v1/question/sse-streaming",
uriBuilder -> uriBuilder
.queryParam("content", "red")
.queryParam("client_id", alanId)
.build())
.retrieve()
.bodyToFlux(String.class)
.flatMap(this::parseJsonToResponseDto);
}
private Flux<AlanResponseDto> parseJsonToResponseDto(String jsonString){
try {
// Parse JSON string to ResponseDto object
AlanResponseDto responseDto = this.objectMapper.readValue(jsonString, AlanResponseDto.class);
return Flux.just(responseDto);
} catch (JsonProcessingException e) {
// Handle parsing exception
return Flux.error(e);
}
}
}
WebClient๋ฅผ ์์ฑํด์ HTTP ์์ฒญ์ ๋ณด๋ด๊ณ ,
Jackson ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ObjectMapper๋ฅผ ์์ฑํด JSON ๋ฌธ์์ด์ AlanResponseDto ๊ฐ์ฒด๋ก ๋ณํํ๋ค.
private final ObjectMapper objectMapper = new ObjectMapper().configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
Jackson์ ๊ธฐ๋ณธ์ ์ผ๋ก JSON ๋ฌธ์์ด์ ํฐ ๋ฐ์ดํ๋ฅผ ์ฌ์ฉํด ๋ฌธ์์ด ๊ฐ์ ํ์ํ๋๋ฐ ์์ ๋ฐ์ดํ๋ฅผ ํ์ฉํ๋๋ก ํ์ฌ ํ์ฑ ์ฒ๋ฆฌํ๋๋ฐ ๋ฌธ์ ์๊ฒ๋ ๋ง๋ค์๋ค.
parseJsonToResponseDto()๋ฉ์๋๋ JSON ๋ฌธ์์ด์ AlanResponseDto ๊ฐ์ฒด๋ก ๋ณํํ๋ค.
AlanResponseDto ๊ฐ์ฒด๋ก ํ์ฑํ๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ฅผ Flux๋ก ๋ฐํํ๋ ๊ฒ์ด๋ค.
์ฐธ๊ณ ์๋ฃ
https://www.baeldung.com/jackson-exception