전에 RequestBody에 들어있는 Json 데이터가 변환하는지 알아야하고 어떠한 형태로 바뀌는 지 확인할 수 있었다.
ObjectMapper가 SpringFreamwork 에서 활용되는 라이브러리지만 꼭 사용되는 것은 아니다.
Json을 관련 된 라이브러리
구글 Gson,
ObjectMapper 등이 있다.
스프링은 ObjectMapper를 많이 사용한다.
Maven Repository: Search/Browse/Explore
Dropwizard Jetty Support Last Release on Jun 30, 2022
mvnrepository.com
스프링 부트의 Repository를 찾는 곳.
여기서 라이브러리를 찾을 수 있다.
보통은 새로운 버전이 나와도 적절하게 가운데 버전을 사용하고 있음을 볼 수 있다.
그 중
2.13 버젼을 사용했다.
Gradle이나 Maven은 의존성을 추가해주는 것만 하더라도 온라인에서 해당 라이브러리를 찾아서 추가해준다.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import dto.Car;
import dto.User;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) throws JsonProcessingException {
System.out.println("main");
ObjectMapper objectMapper = new ObjectMapper();
User user = new User();
user.setName("홍길동");
user.setAge(20);
Car car1 = new Car();
car1.setName("K7");
car1.setCarNumber("11가 1111");
car1.setType("sedan");
Car car2 = new Car();
car2.setName("Audi");
car2.setCarNumber("22가 2222");
car2.setType("SUV");
List<Car> carList = Arrays.asList(car1, car2);
user.setCars(carList);
//System.out.println(user);
String json = objectMapper.writeValueAsString(user);
System.out.println(json);
}
}
간단한 dto를 만들고 결과값을 출력해보았다.
https://jsonformatter.curiousconcept.com/# 사이트를 이용해 Json 형태로 변환해 보았다.
-카멜 케이스로 들어가 있는 것을 스네이크 케이스로,
변수에 직접 변환하거나 클래스에 설정하는 방법 중 변수에 붙이는 방법을 이용했다.
@JsonProperty("Car_number")
private String carNumber;
@JsonProperty("TYPE")
private String type;
순수한 NODE로 접근하는 방법
{
"name":"홍길동",
"age":20,
"cars":[
{
"name":"K7",
"carNumber":"11가 1111",
"type":"sedan"
},
{
"name":"Audi",
"carNumber":"22가 2222",
"type":"SUV"
}
]
}
JsonNode를 이용하는 방법
JsonNode jsonNode = objectMapper.readTree(json);
String _name = jsonNode.get("name").asText();
int _age = jsonNode.get("age").asInt();
System.out.println("name : "+_name);
System.out.println("age : "+_age);
//변수 타입과 이름을 알고 있을때 할 수 있는 경우
cars는 새로운 배열의 노드이다.
JsonNode cars = jsonNode.get("cars");
ArrayNode arraysNode = (ArrayNode)cars;
List<Car> _cars = objectMapper.convertValue(arraysNode, new TypeReference<List<Car>>() {});
//오브젝트를 받아서 List 형태로 변환한다.
System.out.println(_cars);
convertValue로 arraysNode라는 오브젝트를 받고 그것을 List 형태로 변화시키는 방법을 사용했다.
정리) 표준 스펙을 아는 경우 jsonNode.get() 형태로 오브젝트를 가져오고 형변환은 asText(), asInt를 사용.
Array인 경우는 ArrayNode로 형변환을 하고
파싱을 할 경우는 objectMapper속 convertValue를 이용하여 오브젝트를 넣고 원하는 타입으로 매칭을 시켜준다.
Json 형태를 바꿔보자.
ObjectNode objectNode = (ObjectNode) jsonNode;
objectNode.put("name", "steve");
objectNode.put("age", 20);
System.out.println(objectNode.toPrettyString());
어디서 사용할까?
AOP나 Filter 등 순수 Json 형태의 body를 꺼내서 값을 변경할 때 각각의 노드에 대해서 설정을 바꾸거나 치환할 수 있다.
ObjectMapper를 통해서 각각의 Json 노드에 접근하고 변경할 수 있다.
'Spring > Spring 공부' 카테고리의 다른 글
Spring boot 자주 사용되는 어노테이션(Annotations) (0) | 2024.02.16 |
---|---|
6. Spring Boot Annotations (0) | 2022.07.03 |
4. AOP 코딩 실습-2 (0) | 2022.07.02 |
3. AOP 코드 실습 (0) | 2022.07.01 |
2. IOC 코드 실습 (0) | 2022.07.01 |