Jackson - ObjectMapper

김상범·2021년 5월 16일
0

Jackson

데이터 송수신에 필요한 Json 형태로 변환하기 위해 혹은 Json을 받아서 파싱하기위해
Spring에서는 주로 Jackson을 사용한다고한다. (이전 까지 Gson을 많이 사용했었는디...)

gradle

maven repository 에서 가장 인기있는 jackson을 받아왔다

implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.2'

Json

아래 형태의 제이슨을 만들고 이용하겠다.

{
  "name" :"홍길동",
  "age" : 10,
  "cars" : [
    {"name" : "k5",
    "car_number" :"11가",
    "type" : "세단"},
    {"name" : "q5",
    "car_number" :"11가",
    "type" : "suv"}

  ]
}

Class to Json

클래스 형태로 데이터를 삽입해준다.

        User user = new User();
        user.setName("홍길동");
        user.setAge(14);

        Car car = new Car();
        car.setName("k5");
        car.setCarName("11가 1111");
        car.setType("sedan");

        Car car2 = new Car();
        car2.setCarName("11가 1111");
        car2.setType("suv");
        car2.setName("qm5");
        List<Car> carList = Arrays.asList(car,car2);
        user.setCars(carList);
       

삽입 한 데이터를 Json 형태로 가공한다.

        ObjectMapper om = new ObjectMapper();
        String json= om.writeValueAsString(user);

데이터를 출력하면

{
	"name":"홍길동","age":14,"cars":
		[
			{"name":"k5","carName":"11가 1111","type":"sedan"},
            		{"name":"qm5","carName":"11가 1111","type":"suv"}
		]
}

깔금하게 json 형태로 출력 되는 것을 볼 수 있다.

Json to Class

 	JsonNode jsonNode = om.readTree(json);
        String _name = jsonNode.get("name").asText();
        String _age = jsonNode.get("age").asText();
        JsonNode cars = jsonNode.get("cars");
        ArrayNode arrayNode=(ArrayNode) cars;
        List<Car> _cars=om.convertValue(arrayNode,new TypeReference<List<Car>>(){});
       

String 형태의 단일 형은 그냥 가져오면 되지만
List 는 형변환 과정이 필요하다.
아래 코드는 가져온 json 데이터를 수정 하는 과정이다.

	ObjectNode objectNode =(ObjectNode) jsonNode;
        objectNode.put("name","seteve");
        objectNode.put("age","11");

결론

본인은 아직 Gson 이 더 맘에 들지만 익숙해 지면 더 편해 질 수도.. 있을 것 같다. 무엇보다 아래 json 로고 시공 로고랑 비슷하다...

profile
아기개발자

0개의 댓글