JSON 배열은 대괄호([])로 묶인 값들의 순서 있는 컬렉션입니다. 즉, '['로 시작해서 ']'로 끝나며, 배열 내의 값들은 쉼표(,)로 구분됩니다.
JSON 배열 예시
{
"books": [ Java, JavaFX, Hbase, Cassandra, WebGL, JOGL]
}json-simple은 JSON 객체를 처리하기 위해 사용되는 경량 라이브러리입니다. 이 라이브러리를 사용하면 Java 프로그램으로 JSON 문서의 내용을 읽거나 쓸 수 있습니다.
JSON-Simple Maven 의존성 설정
다음은 json-simple 라이브러리의 Maven 의존성입니다.
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>이 코드를 pom.xml 파일 끝부분(</project> 태그 앞)에 있는 <dependencies></dependencies> 태그 사이에 붙여넣으면 됩니다.
예제 준비
먼저 아래와 같이 여러 개의 키-값 쌍과 하나의 배열을 포함하는 sample.json이라는 이름의 JSON 문서를 생성해 보겠습니다.
{
"ID": "1",
"First_Name": "Krishna Kasyap",
"Last_Name": "Bhagavatula",
"Date_Of_Birth": "1989-09-26",
"Place_Of_Birth":"Vishakhapatnam",
"Salary": "25000"
"contact": [
"e-mail: krishna_kasyap@gmail.com",
"phone: 9848022338",
"city: Hyderabad",
"Area: Madapur",
"State: Telangana"
]
}JSON 파일에서 배열을 읽는 단계별 방법
Java 프로그램으로 JSON 파일에서 배열을 읽으려면 다음 순서대로 진행합니다.
1. JSONParser 객체 생성
json-simple 라이브러리의 JSONParser 클래스를 인스턴스화합니다.
JSONParser jsonParser = new JSONParser();
2. parse() 메서드로 파일 파싱
parse() 메서드를 사용하여 JSON 파일의 내용을 파싱합니다.
// JSON 파일의 내용 파싱
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/players_data.json"));3. get() 메서드로 값 가져오기
get() 메서드를 사용하여 특정 키에 연결된 값을 조회할 수 있습니다.
String value = (String) jsonObject.get("key_name");4. JSONArray로 배열 가져오기
다른 요소들과 마찬가지로 get() 메서드를 사용하여 JSON 배열을 JSONArray 객체로 가져옵니다.
JSONArray jsonArray = (JSONArray) jsonObject.get("contact");5. iterator() 메서드로 배열 순회
JSONArray 클래스의 iterator() 메서드는 Iterator 객체를 반환하며, 이를 통해 현재 배열의 내용을 순회할 수 있습니다.
// 배열 내용 순회
Iterator<String> iterator = jsonArray.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}전체 예제 코드
다음 Java 프로그램은 앞서 만든 sample.json 파일을 파싱하고, 그 내용을 읽어 화면에 출력합니다.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadingArrayFromJSON {
public static void main(String args[]) {
// JSONParser 객체 생성
JSONParser jsonParser = new JSONParser();
try {
// JSON 파일의 내용 파싱
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/test.json"));
System.out.println("Contents of the JSON are: ");
System.out.println("ID: "+jsonObject.get("ID"));
System.out.println("First name: "+jsonObject.get("First_Name"));
System.out.println("Last name: "+jsonObject.get("Last_Name"));
System.out.println("Date of birth: "+ jsonObject.get("Date_Of_Birth"));
System.out.println("Place of birth: "+ jsonObject.get("Place_Of_Birth"));
System.out.println("Salary: "+jsonObject.get("Salary"));
// 배열 가져오기
JSONArray jsonArray = (JSONArray) jsonObject.get("contact");
System.out.println("");
System.out.println("Contact details: ");
// 배열 내용 순회
Iterator<String> iterator = jsonArray.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}실행 결과
Contents of the JSON are: ID: 1 First name: Krishna Kasyap Last name: Bhagavatula Date of birth: 1989-09-26 Place of birth: Vishakhapatnam Salary: 25000 Contact details: e-mail: krishna_kasyap@gmail.com phone: 9848022338 city: Hyderabad Area: Madapur State: Telangana
이처럼 json-simple 라이브러리를 활용하면 JSON 파일의 일반 키-값 데이터뿐만 아니라 배열 데이터도 손쉽게 읽고 처리할 수 있습니다. 실제 프로젝트에서는 파일 경로 오류나 잘못된 JSON 형식에 대비해 예외 처리를 반드시 포함하는 것이 좋습니다.