restTemplate.exchange 로 Dto 클래스에 get으로 받는데 값이 안들어와요
조회수 2523회
찾다가 지쳐서 올립니다.
Spring (Boot) Rest Client이고 URL 호출해서 get으로 json 데이터를 받아옵니다.
String으로는 값을 받아오는데
Dto에 값을 넣으면 비어 있네요.
리스트 가지고 오는건 dto 리스트 클래스 만들어서 성공했고요 단일로 dto에 넣는게 안되네요.
http://appsdeveloperblog.com/spring-resttemplate-tutorial/ 참조해서 만들었는데
뭐가 문제 인지 아시는 분은 답변 부탁드려요.
코드1: lombok을 사용한 Dto 클래스
혹시나 lombok이 문젠가.. json 어노테이션을 줘야하나
Dto.java
@Data
public class Dto {
private String str1;
private int int2;
...
코드2: Dto로 받으면 값이 안들어옴
헤더에 id를 넣어야해서 이걸 엔티티에 담아서 restTemplate.exchange 에 넣기위해 이걸 씁니다.
Application.java
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
HttpHeaders headers = new HttpHeaders();
headers.set("id", "myid");
HttpEntity<?> entity = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Dto> response = restTemplate.exchange(
URL,
HttpMethod.GET,
entity,
Dto.class);
System.out.println(response.getBody());
}
16:08:03.611 [main] DEBUG org.springframework.web.client.RestTemplate - HTTP GET URL 16:08:03.648 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[application/json, application/*+json] 16:08:03.746 [main] DEBUG org.springframework.web.client.RestTemplate - Response 200 OK 16:08:03.750 [main] DEBUG org.springframework.web.client.RestTemplate - Reading to [com.example.demo.Dto]
Dto(str1=null, int2=0, ...
코드3: String으로 받으면 정상으로 받아짐
Application.java
ResponseEntity<String> response = restTemplate.exchange(
URL,
HttpMethod.GET,
entity,
String.class);
16:08:03.481 [main] DEBUG org.springframework.web.client.RestTemplate - HTTP GET URL 16:08:03.487 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[text/plain, application/json, application/+json, */] 16:08:03.605 [main] DEBUG org.springframework.web.client.RestTemplate - Response 200 OK 16:08:03.606 [main] DEBUG org.springframework.web.client.RestTemplate - Reading to [java.lang.String] as "application/json"
{"Dto":{"str1":"string","int2":100,...
코드4: get으로 받는 JSON 데이터
{
"Dto": {
"str1": "string",
"int2": 100,
...
},
"statusCode": 200,
"statusDesc": "OK"
}
댓글 입력