JSON 파일로 저장 (json.simple.[JSONObject/JSONArray] )

2023. 3. 2. 15:31JAVA

build.gradle

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
    
    //json-simple 추가
    implementation 'org.json:json:20190722'
    implementation 'com.googlecode.json-simple:json-simple:1.1.1'
}

 

JSONObject

JSONObject obj = new JSONObject();
obj.put("name", "재준")
obj.put("year", 27)
obj.put("hobby", "exercise")

다음과 같이 데이터를 저장하게 되면 다음과 같은 json 형태를 저장할 수 있다.

{"name" : "재준", "year" : 27, "hobby" : "exercise"} 

 

그렇다면 이러한 형태를 여러개 가지고 있는 json형태를 저장하려면 ?

 

JSONArray

JSONArray jArray = new JSONArray( "jsons");

// {"name" : "재준", "year" : 27, "hobby" : "exercise"} 
// {"name" : "승헌", "year" : 26, "hobby" : "soccer"} 
// {"name" : "형원", "year" : 27, "hobby" : "sleep"} 
// 3개의 json을 묶어주기 위해 JSONArray를 선언하였다.

jArray.add(JSONObject 이름)

jsons
  [
    {
      "name": "재준",
      "year": 27,
      "hobby": "exercise"
    },
    {
      "name": "승헌",
      "year": 26,
      "hobby": "soccer"
    },
    {
      "name": "형원",
      "year": 27,
      "hobby": "sleep"
    } 
  ]

다음과 같이 JSONArray (jsons)가 소유하고 있는 json들을 묶을 수 있다.

 

* json 파일을 만들려면 다음과 같이 FileWriter을 사용하면 된다.

  : jsonArray.writeJONString(FileWriter 이름)

try {
            FileWriter file = new FileWriter("json파일이 있는 경로", 이어쓰기(T/F));
            jsonArray.writeJSONString(file);

            file.flush();
            file.close();
} catch (IOException e) {
            e.printStackTrace();
}