SPRING

[Rest API] JSON과 XML로 반환 방법

silver-w 2024. 12. 10. 09:51

Rest API에서는 표준화된 VO 타입 필요하다.

자바에는 익명 객체가 없으므로 MAP을 사용하는데, 이는 클라이언트 등 호출받는 쪽에서 JSON / XML 문자열로 반환된다. 

 

JSON과 XML로 반환 과정

 


 

@RestController
public class UserRest {
	@GetMapping( path = "/userJson", produces = MediaType.APPLICATION_JSON_VALUE)
	public List<Map<String, Object>> userJson() {
    	List<Map<String, Object>> list = new ArrayList<>();
        Map u1 = new HashMap<>();
        Map u2 = new HashMap<>();
        Map u3 = new HashMap<>();
        u1.put("name", "user1");
        u1.put("age", 20);
        list.add(u1);
        u2.put("name", "user2");
        u2.put("age", 20);
        list.add(u2);
        
        return list;
    }
	
	@GetMapping( path = "/userXml", produces = MediaType.APPLICATION_XML_VALUE)
	public List<Map<String, Object>> userXml() {
		List<Map<String, Object>> list = new ArrayList<>();
		Map u1 = new HashMap<>();
		Map u2 = new HashMap<>();
		Map u3 = new HashMap<>();
		u1.put("name", "user1");
		u1.put("age", 20);
		list.add(u1);
		u2.put("name", "user2");
		u2.put("age", 20);
		list.add(u2);
		
		return list;
	}
}

// return list; 
// -> List 형태로 반환을 하더라도, iterator하여 JSON or XML 문자열로 변환되어 반환된다.
// 배열인 경우 List<Map> 으로 넘겨도 된다는 것

 

RestController 에서 JSON 으로 변환이 가능한 이유


@GetMapping( path = "/userJson", produces = MediaType.APPLICATION_JSON_VALUE )
// produces 부분은 디폴트 값이므로 생략 가능

org.springframework.http.MediaType : 전용 변수를 static final로 저장해둔 클래스

□ XML로 변환을 원할 때는 라이브러리를 추가하고 produces 변수 값을 지정해야한다

@GetMapping( path = "/userXml", produces = MediaType.APPLICATION_XML_VALUE)

※ XML 파싱 라이브러리

<dependency>
         <groupId>com.fasterxml.jackson.dataformat</groupId>
         <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

 

RestAPI로 백엔드를 구성할 때에는 JSON 과 XML을 둘다 반환하면 된다.

(Controller 와Rest 를 구분하는 것 처럼 XML와 JSON도 패키지별로 따로 관리하는게 좋다.

'SPRING' 카테고리의 다른 글

@Scheduled / @Validation / View Mapping 방법  (0) 2024.12.10
[LOMBOK]@AllArgsConstructor (롬복기능)  (0) 2024.12.10
DI / Bean(@ComponentScan)  (0) 2024.12.09
Filter / Interceptor / AOP  (0) 2024.12.09
POST-Redirect-GET (PRG) 패턴  (0) 2024.11.30