[java] 자바에서 JSON 데이터의 중첩된 객체 조작하기

JSON (JavaScript Object Notation)은 데이터 교환을 위해 사용되는 경량 데이터 형식입니다. 자바에서는 JSON 데이터를 처리하는 데에 많은 라이브러리가 있으며, 이를 활용하여 중첩된 객체를 조작할 수 있습니다.

1. Gson 라이브러리 사용하기

Gson은 Google에서 제공하는 자바 기반의 JSON 라이브러리로, 강력한 기능과 편리한 API를 제공합니다. Gson을 사용하면 자바 객체와 JSON 데이터를 서로 변환할 수 있으며, 중첩된 객체의 조작도 가능합니다.

import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {
        // JSON 문자열
        String json = "{\"name\":\"John\", \"age\":30, \"address\":{\"city\":\"New York\", \"state\":\"NY\"}}";

        // Gson 객체 생성
        Gson gson = new Gson();

        // JSON 문자열 파싱하여 자바 객체로 변환
        User user = gson.fromJson(json, User.class);

        // 중첩된 객체의 조작
        user.getAddress().setCity("Los Angeles");

        // 자바 객체를 JSON 문자열로 변환
        String updatedJson = gson.toJson(user);

        // 결과 출력
        System.out.println(updatedJson);
    }
}

class User {
    private String name;
    private int age;
    private Address address;

    // getters and setters

    // 중첩된 객체를 나타내는 클래스
    static class Address {
        private String city;
        private String state;

        // getters and setters
    }
}

위의 예제에서는 Gson을 사용하여 JSON 문자열을 파싱하여 자바 객체로 변환하고, 중첩된 객체의 값을 수정한 후 다시 JSON 문자열로 변환해보았습니다.

2. Jackson 라이브러리 사용하기

Jackson은 JSON 데이터 처리를 위한 강력한 라이브러리로, 성능과 유연성 면에서 우수한 평가를 받고 있습니다. Jackson을 사용하여 중첩된 객체를 조작하는 방법을 알아봅시다.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) throws JsonProcessingException {
        // JSON 문자열
        String json = "{\"name\":\"John\", \"age\":30, \"address\":{\"city\":\"New York\", \"state\":\"NY\"}}";

        // ObjectMapper 객체 생성
        ObjectMapper objectMapper = new ObjectMapper();

        // JSON 문자열 파싱하여 JsonNode 객체로 변환
        JsonNode rootNode = objectMapper.readTree(json);

        // 중첩된 객체의 조작
        ((ObjectNode) rootNode.get("address")).put("city", "Los Angeles");

        // JsonNode 객체를 JSON 문자열로 변환
        String updatedJson = objectMapper.writeValueAsString(rootNode);

        // 결과 출력
        System.out.println(updatedJson);
    }
}

위의 예제에서는 Jackson을 사용하여 JSON 문자열을 파싱하여 JsonNode 객체로 변환하고, 중첩된 객체의 값을 수정한 후 다시 JSON 문자열로 변환해보았습니다.

결론

자바에서 JSON 데이터의 중첩된 객체를 조작하는 방법에 대해 알아보았습니다. Gson과 Jackson은 각각 강력한 기능을 제공하여 JSON 데이터를 다루는 작업을 쉽고 효율적으로 처리할 수 있습니다. 사용하는 라이브러리에 따라 개발 환경과 요구사항에 맞게 선택하여 사용하면 됩니다.

참고 자료