Java에서 JSON 처리 과정 중 JSON 파싱과 생성 방법에 대해 알아보겠습니다.

JSON(JavaScript Object Notation)은 데이터를 교환하기 위한 경량 데이터 포맷으로, Java 애플리케이션에서도 널리 사용됩니다. 이번 글에서는 Java에서 JSON 처리 과정 중 JSON 파싱과 생성 방법에 대해 알아 보겠습니다.


1. JSON 처리 라이브러리

Java에서 JSON을 처리하기 위해 가장 많이 사용하는 라이브러리는 다음과 같습니다:

  1. Jackson: 성능이 우수하며, 다양한 기능을 제공합니다.
  2. Gson: Google에서 개발한 간단하고 가벼운 라이브러리.
  3. org.json: 기본적인 JSON 처리 기능을 제공하는 표준 라이브러리.

2. Jackson을 이용한 JSON 처리

Jackson 라이브러리 추가

Maven 프로젝트에서 pom.xml에 다음 종속성을 추가합니다:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.0</version>
</dependency>
  1. JSON 문자열 파싱(Deserialization)
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class JsonParsingExample {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\",\"age\":30}";

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Person person = objectMapper.readValue(jsonString, Person.class);
            System.out.println("이름: " + person.getName());
            System.out.println("나이: " + person.getAge());
        } catch (IOException e) {
            System.out.println("JSON 파싱 오류: " + e.getMessage());
        }
    }
}

class Person {
    private String name;
    private int age;

    // Getter와 Setter
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

출력:

이름: John
나이: 30
  1. JSON 생성(Serialization)
public class JsonCreationExample {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Jane");
        person.setAge(25);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(person);
            System.out.println("생성된 JSON: " + jsonString);
        } catch (IOException e) {
            System.out.println("JSON 생성 오류: " + e.getMessage());
        }
    }
}

출력

생성된 JSON: {"name":"Jane","age":25}

3. Gson을 이용한 JSON 처리

Gson 라이브러리 추가

Maven 프로젝트에서 pom.xml에 다음 종속성을 추가합니다:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.9.0</version>
</dependency>
  1. JSON 파싱
import com.google.gson.Gson;

public class GsonParsingExample {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"Alice\",\"age\":28}";

        Gson gson = new Gson();
        Person person = gson.fromJson(jsonString, Person.class);

        System.out.println("이름: " + person.getName());
        System.out.println("나이: " + person.getAge());
    }
}
  1. JSON 생성
public class GsonCreationExample {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Bob");
        person.setAge(35);

        Gson gson = new Gson();
        String jsonString = gson.toJson(person);

        System.out.println("생성된 JSON: " + jsonString);
    }
}

4. org.json을 이용한 JSON 처리

Java 표준 라이브러리 org.json을 사용하여 JSON을 처리할 수도 있습니다.

  1. JSON 파싱
import org.json.JSONObject;

public class OrgJsonParsingExample {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"Charlie\",\"age\":40}";

        JSONObject jsonObject = new JSONObject(jsonString);
        String name = jsonObject.getString("name");
        int age = jsonObject.getInt("age");

        System.out.println("이름: " + name);
        System.out.println("나이: " + age);
    }
}
  1. JSON 생성
import org.json.JSONObject;

public class OrgJsonCreationExample {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Dave");
        jsonObject.put("age", 45);

        System.out.println("생성된 JSON: " + jsonObject.toString());
    }
}

결론

Java에서 JSON 처리 과정 중 JSON 파싱과 생성 방법에 알아 보았습니다. Java에서 JSON을 처리하기 위해 다양한 라이브러리를 활용할 수 있습니다.

Jackson은 강력한 기능과 성능을 제공하며, Gson은 간단한 JSON 작업에 적합합니다.

또한, org.json은 표준적인 JSON 처리를 위한 기본 옵션으로 사용할 수 있습니다.  다음 블로그는 Spring Framework 입문 중 Spring에 대해 알아 보도록 하겠습니다. 감삽니다.

Leave a Comment