Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java로 JSON 파일 생성 및 작성하는 방법 — json-simple 라이브러리 활용 가이드

JSON이란?

JSON(JavaScript Object Notation)은 사람이 읽기 쉬운 형태의 데이터 교환을 위해 설계된 경량 텍스트 기반 개방형 표준입니다. JSON의 문법 규칙은 C, C++, Java, Python, Perl 등 주요 프로그래밍 언어의 관례와 유사하기 때문에 개발자라면 누구나 쉽게 이해하고 활용할 수 있습니다.

JSON 문서 예시

{
    "book": [
        {
            "id": "01",
            "language": "Java",
            "edition": "third",
            "author": "Herbert Schildt"
        },
        {
            "id": "07",
            "language": "C++",
            "edition": "second",
            "author": "E.Balagurusamy"
        }
    ]
}

json-simple 라이브러리 소개

json-simple은 JSON 객체를 처리하기 위한 대표적인 경량 라이브러리입니다. 이 라이브러리를 활용하면 별도의 복잡한 설정 없이 Java 프로그램만으로 JSON 문서의 내용을 손쉽게 읽고 쓸 수 있습니다.

Maven 의존성 설정

json-simple 라이브러리를 프로젝트에 추가하려면 아래 Maven 의존성을 pom.xml 파일의 <dependencies> 태그 안, 즉 </project> 태그 앞에 붙여넣으면 됩니다.

<dependencies>
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
    </dependency>
</dependencies>

Java로 JSON 파일 생성하는 3단계

Java 프로그램으로 JSON 문서를 만드는 절차는 크게 세 단계로 정리할 수 있습니다.

  1. JSONObject 객체 생성 — json-simple 라이브러리의 JSONObject 클래스를 인스턴스화합니다.
  2. 키-값 쌍 추가put() 메서드를 사용해 필요한 데이터를 JSON 객체에 삽입합니다.
  3. 파일에 기록 — FileWriter 클래스를 통해 생성된 JSON 객체를 파일로 저장합니다.

각 단계별 핵심 코드는 다음과 같습니다.

// JSONObject 객체 생성
JSONObject jsonObject = new JSONObject();
// 키-값 쌍 삽입
jsonObject.put("key", "value");
// FileWriter로 파일에 기록
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();

전체 예제 코드

아래 Java 프로그램은 JSON 객체를 생성한 뒤 output.json이라는 이름의 파일에 저장합니다.

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;

public class CreatingJSONDocument {
    public static void main(String args[]) {
        // JSONObject 객체 생성
        JSONObject jsonObject = new JSONObject();
        // JSON 객체에 키-값 쌍 삽입
        jsonObject.put("ID", "1");
        jsonObject.put("First_Name", "Shikhar");
        jsonObject.put("Last_Name", "Dhawan");
        jsonObject.put("Date_Of_Birth", "1981-12-05");
        jsonObject.put("Place_Of_Birth", "Delhi");
        jsonObject.put("Country", "India");
        try {
            FileWriter file = new FileWriter("E:/output.json");
            file.write(jsonObject.toJSONString());
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("JSON file created: " + jsonObject);
    }
}

실행 결과

JSON file created: {
"First_Name":"Shikhar",
"Place_Of_Birth":"Delhi",
"Last_Name":"Dhawan",
"Country":"India",
"ID":"1",
"Date_Of_Birth":"1981-12-05"}

생성된 output.json 파일의 내용을 열어 확인해 보면, 코드에서 입력한 데이터가 그대로 저장되어 있는 것을 볼 수 있습니다.

Java로 JSON 파일 생성 및 작성하는 방법 — json-simple 라이브러리 활용 가이드