반응형

# JSON API 활용  (JSON-Java)

## JSON-Java API 다운로드 및 적용방법. (mvnrepository, Build Path)

 

Maven Repository: org.json » json

JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ The files in this package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON and XML, HTTP headers, Cookies, and

mvnrepository.com

  • 다운로드 받은 jar 파일의 경우 별도의 공간(C:\JavaTPC\lib 등..) 에 저장 후 아래와 같이 설정 진행. 
  1. 프로젝트 우 클릭 Build Path > configure Build Path 클릭.
  2. Libraries > Add External JARs 클릭하여 저장한 jar 파일 추가. (자바가 12버전 이상인 경우 Modulepath(자바모듈) 와 Classpath(외부 API 모듈)로 나누어 표시(관리)되어 있어서 Classpath에 추가해주면 되는데, 자바가 그 이전 버전인 경우에는 Add ExternalJARs 해서 바로 추가해주면 됨) 
  3. 완료 후 아래와 같이 Referenced Libraries에 해당 API가 추가되어있는지 확인, 사용 시에는 import 하여 사용하면 된다.

## JSON-Jave API 사용.

1. JSONObject

  • JSONObject 사용
  • JSONObject로 별도의 객체 생성없이 JSON 구조 생성.
import org.json.JSONObject;

public class Project01_B {
	public static void main(String[] args) {
		// JSON-Java(org.json)
		JSONObject student = new JSONObject();
		student.put("name", "김철수");
		student.put("age", 25);
		student.put("phone", "010-1234-1234");
		student.put("address", "세종시 소담동");

		System.out.println(student);
	}
}
  • 출력 결과.
{"address":"세종시 소담동","phone":"010-1234-1234","name":"김철수","age":25}

2. JSONArray

JSONObject, JSONArray 사용.

JSONObject로 객체 생성 후 JSONArray에 담기.

import org.json.JSONArray;
import org.json.JSONObject;

public class Project01_B {
	public static void main(String[] args) {
		// JSON-Java(org.json)
		JSONArray students = new JSONArray();
		
		JSONObject student = new JSONObject();
		student.put("name", "김철수");
		student.put("age", 25);
		student.put("phone", "010-1234-1234");
		student.put("address", "세종시 소담동");

		students.put(student);
		
		System.out.println(student);
		
		student = new JSONObject();
		student.put("name", "신짱구");
		student.put("age", 25);
		student.put("phone", "010-4321-4321");
		student.put("address", "세종시 대평동");

		students.put(student);
		
		System.out.println(student);
		
		JSONObject object = new JSONObject();
		object.put("students", students);
		
		System.out.println(object.toString(2));	
		
	}
}
  • 출력 결과.
{"address":"세종시 소담동","phone":"010-1234-1234","name":"김철수","age":25}
{"address":"세종시 대평동","phone":"010-4321-4321","name":"신짱구","age":25}
{"students": [
  {
    "address": "세종시 소담동",
    "phone": "010-1234-1234",
    "name": "김철수",
    "age": 25
  },
  {
    "address": "세종시 대평동",
    "phone": "010-4321-4321",
    "name": "신짱구",
    "age": 25
  }
]}

3. JSONTokener

  • InputStream JSONTokener, JSONObject, JSONArray 사용
  • InputStream 으로 info.json 파일의 데이터를 읽어와서, JSONTokener로 읽어온 문자열을 JSON으로 변환, JSONObject로 JSON을 JSONObject 로 변환, 변환된 JSONObject를 JSONArray에 담고, 담긴 내역 출력.

  • info.json
{"students": [
  {
    "address": "세종시 소담동",
    "phone": "010-1234-1234",
    "name": "김철수",
    "age": 25
  },
  {
    "address": "세종시 대평동",
    "phone": "010-4321-4321",
    "name": "신짱구",
    "age": 25
  }
]}
import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

public class Project01_C {
	public static void main(String[] args) {
		
		String src = "info.json";
		
		// file에서 데이터 읽어오기. 
		// IO -> Stream (스트림)
		InputStream is = Project01_C.class.getResourceAsStream(src);
		
		if (is == null) {	// 파일이 없는 경우.
			throw new NullPointerException("Can't find resource file");
		}
		
		// file에서 가져온 문자열 -> JSON 객체로 변환.
		JSONTokener tokener = new JSONTokener(is);
		
		// JSON -> JSONObject 변환.
		JSONObject object = new JSONObject(tokener);
		
		JSONArray students = object.getJSONArray("students");
		
		for (int i = 0; i < students.length(); i++) {
			JSONObject student = (JSONObject) students.get(i);	// JSONObject로 객체 받기.
			System.out.println(student.get("name") + "\t" + student.get("age") + "\t" + student.get("address") + "\t" + student.get("phone"));
		}
	}
}
  • 출력결과
김철수	25	세종시 소담동	010-1234-1234
신짱구	25	세종시 대평동	010-4321-4321
반응형

+ Recent posts