คลาส net.sf.json.JSONArray เป็น ลำดับที่มีเรียงลำดับ (ordered sequence) ของค่า รูปแบบภายนอกคือ string ครอบด้วย square brackets คั่นด้วย comma รูปแบบภายในคือ object ที่มีเมธอด get() และ opt() สำหรับเข้าถึงค่าผ่าน index และเมธอด element() สำหรับเพิ่ม/แทนที่ค่า ค่าสามารถเป็นชนิดใดก็ได้: Boolean, JSONArray, JSONObject, Number, String และ JSONNull object
ตัวอย่างการใช้งาน
import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
public class ConvertCollectionToJsonArrayTest {
public static void main(String[] args) {
List<String> strList = Arrays.asList("India", "Australia", "England", "South Africa");
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(strList);
System.out.println(jsonArray.toString(3)); // pretty print JSON
List<Object> mixedList = Arrays.asList("List Data", 50, 99, 50.65, true, new char[]{'X', 'Y', 'Z'});
JSONArray jsonArray2 = (JSONArray) JSONSerializer.toJSON(mixedList);
System.out.println(jsonArray2.toString(3));
}
}
ผลลัพธ์ (Output)
[
"India",
"Australia",
"England",
"South Africa"
]
[
"List Data",
50,
99,
50.65,
true,
[
"X",
"Y",
"Z"
]
]
คำอธิบาย
JSONSerializer.toJSON() สามารถรับ Collection (List, Set, etc.) และแปลงเป็น JSONArray อัตโนมัติ รองรับ:
- Homogeneous collections (List<String>)
- Heterogeneous collections (List<Object> mixed types)
- Nested collections/arrays
- Null elements
Collection Types ที่รองรับ
List(ArrayList, LinkedList) - รักษาลำดับSet(HashSet, TreeSet) - ลำดับไม่แน่นอน (HashSet) หรือเรียง (TreeSet)Queue- ตามลำดับ queue- Arrays - ผ่าน Arrays.asList()
สรุป
JSONSerializer.toJSON() ให้การแปลง Collection ใดๆ เป็น JSONArray ได้อย่างตรงไปตรงมาและอัตโนมัติ เป็นวิธีที่สะดวกที่สุดสำหรับการ serialize collections ใน JSON-lib