JSON Array คอลเลกชันค่าลำดับใน [ ... ] คั่น comma ใช้ json-simple library อ่านได้
Maven Dependency
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
ไฟล์ JSON ตัวอย่าง (sample.json)
{
"ID": "1",
"First_Name": "Krishna Kasyap",
"Last_Name": "Bhagavatula",
"Date_Of_Birth": "1989-09-26",
"Place_Of_Birth": "Vishakhapatnam",
"Salary": "25000",
"contact": [
"e-mail: krishna_kasyap@gmail.com",
"phone: 9848022338",
"city: Hyderabad",
"Area: Madapur",
"State: Telangana"
]
}
ขั้นตอนอ่าน JSON Array
- สร้าง JSONParser
- Parse ไฟล์ด้วย parse(FileReader) ได้ JSONObject
- ดึงค่าปกติด้วย get("key")
- ดึง Array ด้วย get("contact") cast เป็น JSONArray
- วนลูปด้วย iterator() ของ JSONArray
ตัวอย่างโค้ดเต็ม
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
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 ReadingArrayFromJSON {
public static void main(String args[]) {
JSONParser jsonParser = new JSONParser();
try {
// Parse JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/test.json"));
System.out.println("Contents of the JSON are: ");
System.out.println("ID: " + jsonObject.get("ID"));
System.out.println("First name: " + jsonObject.get("First_Name"));
System.out.println("Last name: " + jsonObject.get("Last_Name"));
System.out.println("Date of birth: " + jsonObject.get("Date_Of_Birth"));
System.out.println("Place of birth: " + jsonObject.get("Place_Of_Birth"));
System.out.println("Salary: " + jsonObject.get("Salary"));
// ดึง Array
JSONArray jsonArray = (JSONArray) jsonObject.get("contact");
System.out.println("\nContact details: ");
// Iterate array
Iterator iterator = jsonArray.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException | IOException | ParseException e) {
e.printStackTrace();
}
}
}
ผลลัพธ์
Contents of the JSON are:
ID: 1
First name: Krishna Kasyap
Last name: Bhagavatula
Date of birth: 1989-09-26
Place of birth: Vishakhapatnam
Salary: 25000
Contact details:
e-mail: krishna_kasyap@gmail.com
phone: 9848022338
city: Hyderabad
Area: Madapur
State: Telangana
หมายเหตุ
- json-simple คืนค่าเป็น Object ต้อง cast
- JSONArray.iterator() คืน Iterator ของค่าใน array
- จัดการ Exception: FileNotFoundException, IOException, ParseException