-JAVA 프로젝트에서 objectmapper 사용하기
1. 의존성 추가
2. utf-8 로 인코딩 되게 하기 (->안하면 오류남)
(참고) 매핑할 json형태
https://jsonformatter.curiousconcept.com/# 에서 json형식이 올바른지 확인 가능
- object mapper => java에서 사용하는 거지 spring에만 국한된게 아님.. 고로 스프링프로젝트가 아닌 (Gradle)자바 프로젝트로 해보겄다!!
- springboot의 dependency를 어디서 얻어올까 ? => https://mvnrepository.com/ 에 검색해서!
- 자바 프로젝트 이므로 의존성 추가, UTF-8 설정을 해줘야 오류없이 됨 -> 자세한건 스샷 참고
public class Main {
public static void main(String[] args) throws JsonProcessingException {
// objectMapper.readValue()로 json->객체 할 수 있겠지만 다른 방법으로도 해보자
// 객체 전체가 아닌, 필요한 키-값을 가져올 수 있다.
System.out.println("main");
ObjectMapper objectMapper=new ObjectMapper();
User user=new User();
user.setName("홍길동");
user.setAge(26);
Car car1=new Car();
car1.setName("붕붕이");
car1.setCarNumber("45가 3242");
car1.setType("SUV");
Car car2=new Car();
car2.setName("씽씽이");
car2.setCarNumber("34가 5532");
car2.setType("세단");
List<Car> carList= Arrays.asList(car1,car2); // 변수 두개를 리스트로 묶기! => Arrays.asList(a,b)
user.setCars(carList);
System.out.println(user);
//object를 json으로 변환
String json=objectMapper.writeValueAsString(user);
System.out.println(json);
//json에서 object 각 속성들을 가져오기
JsonNode jsonNode=objectMapper.readTree(json); //json을 노드로 취급, 가져오기
String name=jsonNode.get("name").asText(); //get("키") 하면 값을 가져올 수 있음
int age=jsonNode.get("age").asInt();
System.out.println(name);
System.out.println(age);
//그렇담 json 배열은 어캄?
JsonNode cars=jsonNode.get("cars"); // 어쨌든 배열도 또다른 json이니 json노드로 받아준다.
ArrayNode arrayNode=(ArrayNode) cars; // 노드를 배열노드로 받아줌
List<Car> _cars=objectMapper.convertValue(arrayNode, new TypeReference<List<Car>>() {}); //객체 배열로 드디어 변환;
System.out.println(cars);
//json노드의 값을 바꿔보자
ObjectNode objectNode=(ObjectNode) jsonNode;
objectNode.put("name","steve"); //put,set 모두 키(좌)의 값(우)를 바꿔줌 (여기선, name->steve)
objectNode.put("age",20);
System.out.println(objectNode.toPrettyString()); //objectNode를 예쁜 json 형태로 바꿔 주는 것
}
}
'BackEnd > 패캠' 카테고리의 다른 글
Exception 처리 (0) | 2022.01.22 |
---|---|
Validation (0) | 2022.01.21 |
AOP (0) | 2022.01.19 |
Ioc, DI (0) | 2022.01.18 |
모범사례 - Object Mapper (0) | 2022.01.17 |
Comment