>  기사  >  Java  >  자바의 JSON

자바의 JSON

WBOY
WBOY원래의
2024-08-30 16:02:12482검색

가벼워서 텍스트 기반이고 언어에 독립적이며 사람과 기계 모두 쉽게 읽고 쓸 수 있는 데이터 교환 형식은 Java에서 JSON이라고도 하는 JavaScript Object Notation입니다. 이는 객체와 배열이라는 두 가지 유형의 구조를 나타냅니다. 여기서 객체는 0개 이상의 이름 및 값 쌍으로 구성된 컬렉션이고 순서가 지정되지 않은 컬렉션이며, 값이 없거나 0보다 많은 순서가 지정된 시퀀스는 배열입니다. 가능한 값은 숫자, 문자열, 부울, Null, 객체, 배열이 될 수 있습니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java에서 JSON 작업

  • 사람을 설명하기 위해 JSON에서 개체를 나타내는 아래 예를 고려하세요.
  • 이름과 성은 개체의 문자열 값을 취합니다. age는 객체의 숫자 값을 취합니다. address는 문자열과 숫자 값을 사용하여 객체에 있는 사람의 주소를 나타냅니다. 전화번호는 객체의 배열 값을 취합니다.

코드:

{
"fName": "Shobha",
"lName": "Shivakumar",
"age1": 28,
"address1":
{
"streetAdd": "4, Ibbani street",
"city1": "Bangalore",
"state1": "Karnataka",
"pinCode": 560064
},
"phNumbers":
[
{
"type1": "home1",
"no": "9738128018"
},
{
"type2": "fax1",
"no1": "6366182095"
}
]
}
  • Java에서 JSON(JavaScript Object Notation) 처리는 JavaScript Object Notation(예: JSON.simple)을 사용하는 Java 애플리케이션 프로그래밍 인터페이스를 통해 수행됩니다. JavaScript Object Notation JSON.simple은 JavaScript 객체를 구문 분석할 수 있는 Java 라이브러리입니다. 표기법, JavaScript 객체 표기법 생성, JavaScript 객체 표기법 변환, JavaScript 객체 표기법 쿼리 등
  • JavaScript Object Notation 단순 라이브러리를 사용하려면 JavaScript Object Notation 프로그래밍 예제를 컴파일하고 실행하기 전에 json-simple-1.1.jar을 다운로드하여 CLASS PATH에 넣어야 합니다.
  • JavaScript Object Notation 객체와 배열의 구조는 JavaScript Object Notation 단순 응용 프로그래밍 인터페이스에서 제공하는 객체 모듈을 사용합니다.
  • 이러한 JavaScript 개체 표기법 구조는 JSON 개체 및 JSON 배열 유형을 사용하여 개체 모델로 표현됩니다. JSON 객체는 모델에서 0개 이상의 이름 및 값 쌍 컬렉션에 액세스할 수 있는 맵 뷰를 제공합니다. 이는 정렬되지 않은 컬렉션이며 JSON 배열은 모델의 배열에서 0개 이상의 값이 없거나 0개 이상의 정렬된 시퀀스에 액세스할 수 있는 목록 보기를 제공합니다.

Java의 JSON 예

아래는 Java로 작성된 JSON의 예입니다.

예시 #1

Java에서 JSON(JavaScript Object Notation) 인코딩을 시연하는 Java 프로그램

코드:

//Importing JSON simple library
import org.json.simple.JSONObject;
//Creating a public class
public class JsonEncode {
//Calling the main method
public static void main(String[] args) {
//Creating an object of JSON class
JSONObject obje = new JSONObject();
//Entering the values using the created object
obje.put("bal", new Double(100.22));
obje.put("number", new Integer(200));
obje.put("check_vvip", new Boolean(true));
obje.put("name1", "sean");
//Printing the values through the created object
System.out.print(obje);
}
}

위의 예에서는 JSON 개체 개체가 생성됩니다. JSON 객체 obje를 사용합니다. double, 정수, 부울, 문자열 등과 같은 값이 출력으로 인쇄됩니다.

출력:

자바의 JSON

예시 #2

JSON 객체와 JSON 배열의 사용을 보여주는 Java 프로그램

코드:

//importing JSON simple libraries
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
//creating a public class
public class JsonDecode{
//calling the main method
public static void main(String[] args) {
//creating an object of JSONparser
JSONParser par = new JSONParser();
//defining and assigning value to a string
String str = "[2,{\"3\":{\"4\":{\"5\":{\"6\":[7,{\"8\":9}]}}}}]";
try{
Object objc = par.parse(str);
//creating a JSON array
JSONArray array = (JSONArray)objc;
System.out.println("The array's second element is");
System.out.println(array.get(1));
System.out.println();
//creating a JSON object
JSONObject objc2 = (JSONObject)array.get(1);
System.out.println("Field \"2\"");
System.out.println(objc2.get("2"));
str = "{}";
objc = par.parse(str);
System.out.println(objc);
str = "[7,]";
objc = par.parse(str);
System.out.println(objc);
str = "[7,,2]";
objc = par.parse(str);
System.out.println(objc);
}catch(ParseException pr) {
System.out.println("The elements position is: " + pr.getPosition());
System.out.println(pr);
}
}
}

위의 예에서는 JSON 파서 par의 JSON 객체가 생성된 후 문자열 값이 정의되고 할당됩니다. 문자열에서 서로 다른 지정된 요소를 얻기 위해 JSON 배열이 생성됩니다.

출력:

자바의 JSON

예시 #3

JavaScript Object Notation 개체와 JavaScript 개체 표기법 배열을 사용하여 JSON.json이라는 이름의 파일에 JavaScript 개체 표기법 데이터를 작성하는 Java 프로그램

코드:

//importing java simple libraries and JSON libraries
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JSONWrite
{
public static void main(String[] args) throws FileNotFoundException
{
// Json object is created
JSONObject job = new JSONObject();
// Adding data using the created object
job.put("fName", "Shobha");
job.put("lName", "Shivakumar");
job.put("age1", 28);
// LinkedHashMap is created for address data
Map m1 = new LinkedHashMap(4);
m1.put("streetAdd", "4, Ibbani Street");
m1.put("city1", "Bangalore");
m1.put("state1", "Karnataka");
m1.put("pinCode", 560064);
// adding address to the created JSON object
job.put("address1", m1);
// JSONArray is created to add the phone numbers
JSONArray jab = new JSONArray();
m1 = new LinkedHashMap(2);
m1.put("type1", "home1");
m1.put("no", "9738128018");
// adding map to list
jab.add(m1);
m1 = new LinkedHashMap(2);
m1.put("type2", "fax1");
m1.put("no1", "6366182095");
// map is added to the list
jab.add(m1);
// adding phone numbers to the created JSON object
job.put("phoneNos", jab);
// the JSON data is written into the file
PrintWriter pwt = new PrintWriter("JSON.json");
pwt.write(job.toJSONString());
pwt.flush();
pwt.close();
}
}

위의 예에서는 JSON 개체 작업이 생성되었습니다. 이름, 성, 나이는 작업 개체를 사용하여 JSON.json 파일에 기록됩니다. 연결된 해시 맵이 생성되어 주소 세부 정보를 추가한 다음 JSON 작업 개체를 사용하여 파일에 기록됩니다. 전화번호를 추가하기 위해 JSON 배열 객체가 생성되고, 연결된 해시 맵을 사용하여 다양한 유형의 전화번호를 생성합니다. 마지막으로 JSON 작업 개체를 사용하여 이러한 전화번호를 파일에 기록합니다. 최종적으로 인쇄기를 사용하여 내용을 파일에 기록하게 됩니다.

출력:

위 프로그램의 출력은 파일 내용을 보기 위해 JSON.json 파일에 액세스한 경우입니다.

Note: Since JSON is an unordered collection of name or value pairs, there is no order preserved in the output shown below. 자바의 JSON

Example #4

Java program to read the contents of the file JSON. JSON demonstrates the use of JavaScript Object Notation object parser, JavaScript Object Notation object, and JavaScript Object Notation object array.

Code:

//importing JSON simple libraries
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
public class JSONRead
{
public static void main(String[] args) throws Exception
{
// The file JSON.json is parsed
Object objc = new JSONParser().parse(new FileReader("JSON.json"));
// objc is convereted to JSON object
JSONObject job = (JSONObject) objc;
// obtaining the fname and lname
String fName = (String) job.get("fName");
String lName = (String) job.get("lName");
System.out.println(fName);
System.out.println(lName);
// age is obtained
long age1 = (long) job.get("age1");
System.out.println(age1);
// address is obtained
Map address1 = ((Map)job.get("address1"));
// iterating through the address
Iterator<Map.Entry> itr = address.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pair1 = itr1.next();
System.out.println(pair1.getKey() + " : " + pair1.getValue());
}
// phone numbers are obtained
JSONArray jab = (JSONArray) job.get("phoneNos");
// iterating phoneNumbers
Iterator itr1 = jab.iterator();
while (itr1.hasNext())
{
itr = ((Map) itr1.next()).entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pair1 = itr.next();
System.out.println(pair1.getKey() + " : " + pair1.getValue());
}
}
}
}

In the above example, the file JSON.json is parsed by creating an object objc which is then converted to a JSON object job. First name, last name, age, address, and phone numbers are read from the JSON.json file through iterations and printed as the output.

Output:

The output of the above program after reading the contents from the JSON.json file is shown in the snapshot below:

자바의 JSON

위 내용은 자바의 JSON의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바 디렉토리다음 기사:자바 디렉토리