JSON 또는 JavaScript Object Notation은 사람이 읽을 수 있는 데이터 교환을 위해 설계된 가벼운 텍스트 기반 개방형 표준입니다. C, C++, Java, Python, Perl 등 JSON에서 사용하는 규칙은 프로그래머에게 알려져 있습니다. 샘플 JSON 문서 -
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
} Json 단순 라이브러리
json-simple은 JSON 객체를 처리하는 데 사용되는 경량 라이브러리입니다. 이를 사용하여 Java 프로그램을 사용하여 JSON 문서의 내용을 읽거나 쓸 수 있습니다.
JSON-Simple maven 종속성
다음은 JSON 단순 라이브러리에 대한 maven 종속성입니다. -
<dependencies> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> 301 to 305 </dependencies>
이것을 pom.xml 파일 끝에 있는
예시
먼저 JSON 을 생성하겠습니다. 이름이 sample.json인 문서 아래와 같이 6개의 키-값 쌍으로 -
{
"ID": "1",
"First_Name": "Shikhar",
"Last_Name": "Dhawan",
"Date_Of_Birth": "1981-12-05",
"Place_Of_Birth":"Delhi",
"Country": "India"
} Java 프로그램을 사용하여 JSON 파일의 내용을 읽으려면 -
- json-simple 라이브러리의 JSONParser 클래스를 인스턴스화합니다.
JSONParser jsonParser = new JSONParser();
- parse()를 사용하여 얻은 객체의 내용을 구문 분석합니다. 방법.
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/players_data.json")); - get()을 사용하여 키와 연결된 값 검색 방법.
String value = (String) jsonObject.get("key_name"); 다음 Java 프로그램은 위에서 생성된 sample.json을 구문 분석합니다. 파일의 내용을 읽고 표시합니다.
예시
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadingJSON {
public static void main(String args[]) {
//Creating a JSONParser object
JSONParser jsonParser = new JSONParser();
try {
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/sample.json"));
String id = (String) jsonObject.get("ID");
String first_name = (String) jsonObject.get("First_Name");
String last_name = (String) jsonObject.get("Last_Name");
String date_of_birth = (String) jsonObject.get("Date_Of_Birth");
String place_of_birth = (String) jsonObject.get("Place_Of_Birth");
String country = (String) jsonObject.get("Country");
//Forming URL
System.out.println("Contents of the JSON are: ");
System.out.println("ID :"+id);
System.out.println("First name: "+first_name);
System.out.println("Last name: "+last_name);
System.out.println("Date of birth: "+date_of_birth);
System.out.println("Place of birth: "+place_of_birth);
System.out.println("Country: "+country);
System.out.println(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
} 출력
Contents of the JSON are: ID :1 First name: Shikhar Last name: Dhawan Date of birth :1981-12-05 Place of birth: Delhi Country: India