📙Language/☕Java

[Java] Jackson Databind 이용하기

waveofmymind 2023. 3. 2. 14:52
자바의 객체, 즉 Object를 Json 데이터로 변환할 때 사용할 수 있는 라이브러리

의존성 추가


gradle 기준, build.gradle에 다음과 같은 의존성을 추가합니다.

implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.7.1'

ObjectMapper


import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        // ObjectMapper 객체 생성
        ObjectMapper objectMapper = new ObjectMapper();

        // JSON 문자열
        String json = "{ \"name\": \"Alice\", \"age\": 25 }";

        // JSON 문자열을 자바 객체로 매핑
        Person person = objectMapper.readValue(json, Person.class);

        // 자바 객체를 JSON 문자열로 변환
        String jsonString = objectMapper.writeValueAsString(person);
        System.out.println(jsonString); // 출력: {"name":"Alice","age":25}
    }
}

class Person {
    private String name;
    private int age;

    // 기본 생성자, getter, setter 생략
}
  • ObjectMapper 클래스를 이용해서 Json 데이터를 자바 객체로, 또는 반대로 변환할 수 있습니다.
  • objectMapper.readValue(json데이터, 바꿀 객체 클래스)로 Json 데이터를 객체로 변환할 수 있습니다.
  • objectMapper.writeValueAsString(객체)를 이용하여 객체 내의 필드를 Json 문자열로 변환해서 나타낼 수 있습니다.