java에서 json 포맷 사용방법
java 프로젝트에서 JSON 을 사용하기 위해서 준비물
필자가 사용한 파일은 json-simple-1.1.1.jar 이다.
해당 파일을 다운로드 한 후 이클립스 프로젝트에 넣었다.
또한 독립적인 java programming을 위하여 이전에 설명했던,
JRE :
C:\Program Files\ojdkbuild\java-1.8.0-openjdk-1.8.0.232-1\jre\lib\ext
JDK :
C:\Program Files\ojdkbuild\java-1.8.0-openjdk-1.8.0.232-1\lib\ext
해당 부분에도 파일을 넣어서 적용하였다. (oracle jdk 인 경우 다른 폴더경로)
buildpath 설정
해당 설정은 eclipse - Project - Java Build Path - Libraries - Add JARs…
해당 부분도 적용한다.
적용 이후 다음과 같이 프로젝트에 import를 한다.
import org.json.simple.*;
이중 사용할 수 있는 JSON 포맷은 JSONObject, JSONArray이다.
JSONObject
JSONObject같은 경우엔 java.util.Map 의 구현체이다. 따라서 다음과 같이 사용이 가능하다.
public void setJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Name", "dnetfw"); // string 형 넣기
jsonObject.put("Age", 26); // int 형 넣기
String Name2 = jsonObject.get(0).toString(); // string형 반환
int Age2 = (int)jsonObject.get(1); // int 형 반환
}
결과 :
jsonObject -> {“Name” : “dnetfw” , “Age” : 26}
Name2 -> dnetfw, Age2 -> 26
JSONArray
JSONArray같은 경우엔 java.util.List 의 구현체이다.
따라서 다음과 같이 사용이 가능하다.
public void setJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Name", "dnetfw");
jsonObject.put("Age", 26);
String Name2 = jsonObject.get(0).toString();
int Age2 = (int)jsonObject.get(1);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("Name", "test");
jsonObject2.put("Age", 33);
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObject);
jsonArray.add(jsonObject2);
}
결과 :
jsonObject -> {“Name” : “dnetfw” , “Age” : 26}
Name2 -> dnetfw, Age2 -> 26
jsonObject2 -> {“Name” : “test” , “Age” : 33}
jsonArray ->[{“Name” : “dnetfw” , “Age” : 26}, {“Name” : “test” , “Age” : 33}]
파싱방법은 다음번에 설명하겠다.