웹사이트 검색

json-간단한 예


json-simple은 JSON을 위한 간단한 자바 툴킷입니다. json-simple 라이브러리는 JSON 사양(RFC4627)을 완전히 준수합니다.

json-단순

json-간단한 메이븐

여기에서 다운로드하여 json-simple 라이브러리를 프로젝트에 추가할 수 있습니다. json-simple은 maven 중앙 저장소에서 사용할 수 있으므로 가장 좋은 방법은 pom.xml 파일에 종속성을 추가하는 것입니다.

<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1.1</version>
</dependency>

JSON을 파일에 쓰는 json-simple 예제

json-simple API에서 가장 중요한 클래스는 org.json.simple.JSONObject입니다. 우리는 JSONObject의 인스턴스를 생성하고 여기에 키-값 쌍을 넣습니다. JSONObject toJSONString 메서드는 파일에 쓸 수 있는 문자열 형식의 JSON을 반환합니다. JSON 키에 목록을 작성하려면 org.json.simple.JSONArray를 사용할 수 있습니다.

package com.journaldev.json.write;

import java.io.FileWriter;
import java.io.IOException;

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

public class JsonSimpleWriter {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		JSONObject obj = new JSONObject();
		
		obj.put("name", "Pankaj Kumar");
		obj.put("age", new Integer(32));

		JSONArray cities = new JSONArray();
		cities.add("New York");
		cities.add("Bangalore");
		cities.add("San Francisco");

		obj.put("cities", cities);

		try {

			FileWriter file = new FileWriter("data.json");
			file.write(obj.toJSONString());
			file.flush();
			file.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.print(obj.toJSONString());

	}

}

위의 클래스는 data.json을 작성하고 아래는 이 파일의 JSON 내용입니다.

{"cities":["New York","Bangalore","San Francisco"],"name":"Pankaj Kumar","age":32}

@SuppressWarnings(unchecked) 기본 메서드가 보이시나요? 이는 형식 안전과 관련된 경고를 피하기 위해 수행되었습니다. JSONObject는 HashMap을 확장하지만 Generics를 지원하지 않으므로 Eclipse IDE는 아래와 같이 경고합니다.

유형 안전성: 메소드 put(Object, Object)은 원시 유형 HashMap에 속합니다. 일반 유형 HashMap에 대한 참조는 매개변수화되어야 합니다.

파일에서 JSON을 읽는 json-간단한 예

파일에서 JSON을 읽으려면 org.json.simple.parser.JSONParser 클래스를 사용해야 합니다. JSONParser parse 메서드는 JSONObject를 반환합니다. 그런 다음 키 이름을 전달하여 값을 검색할 수 있습니다. 아래는 파일에서 JSON을 읽는 json-simple 예제입니다.

package com.journaldev.json.write;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
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 JsonSimpleReader {

	public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {
		JSONParser parser = new JSONParser();
		Reader reader = new FileReader("data.json");

		Object jsonObj = parser.parse(reader);

		JSONObject jsonObject = (JSONObject) jsonObj;

		String name = (String) jsonObject.get("name");
		System.out.println("Name = " + name);

		long age = (Long) jsonObject.get("age");
		System.out.println("Age = " + age);

		JSONArray cities = (JSONArray) jsonObject.get("cities");
		
		@SuppressWarnings("unchecked")
		Iterator<String> it = cities.iterator();
		while (it.hasNext()) {
			System.out.println("City = " + it.next());
		}
		reader.close();
	}

}

위의 json-simple 예제는 다음 출력을 생성합니다.

Name = Pankaj Kumar
Age = 32
City = New York
City = Bangalore
City = San Francisco

이것이 json-simple의 빠른 정리를 위한 전부입니다. 그러나 복잡한 JSON 데이터로 작업하려면 Java 7에 추가된 JSR353을 사용해야 합니다.