JSON 파일로 저장 (json.simple.[JSONObject/JSONArray] )
2023. 3. 2. 15:31ㆍJAVA
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();
}
'JAVA' 카테고리의 다른 글
[JAVA] 게시판 등에 자주 사용되는 "몇 분전, 몇 시간전, 2일전" 이런 표현 나타내기 (0) | 2023.05.02 |
---|---|
[JAVA] HashMap 구현 - Hash 값으로 index 만들어서 검색 효율 높이기 (0) | 2023.04.20 |
JSON 파일(데이터) 읽기/파싱 (json.simple.JSONParser) (0) | 2023.03.02 |
예외 (Exception) 간단 정리 (0) | 2023.01.29 |