JSONSerializer.toJSON(Collection) chuyển List/Set → JSONArray. JSON-lib đã cũ, khuyến nghị Jackson/Gson.
Ví dụ minh họa
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import java.util.*;
public class CollectionToJsonArrayTest {
public static void main(String[] args) {
// List String đơn giản
List<String> strList = Arrays.asList("India", "Australia", "England", "South Africa");
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(strList);
System.out.println("String List:\n" + jsonArray.toString(3));
// List Object phức tạp
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("Mixed List:\n" + jsonArray2.toString(3));
}
}
Output
String List:
[ "India", "Australia", "England", "South Africa" ]
Mixed List:
[ "List Data", 50, 99, 50.65, true, [ "X", "Y", "Z" ] ]
Alternative: Jackson (Khuyến nghị)
ObjectMapper mapper = new ObjectMapper();
List<String> list = Arrays.asList("A", "B", "C");
String json = mapper.writeValueAsString(list); // ["A","B","C"]
// Hoặc JsonNode tree model
JsonNode node = mapper.valueToTree(list);
Alternative: Gson
Gson gson = new Gson();
String json = gson.toJson(list); // ["A","B","C"]
JsonArray array = gson.toJsonTree(list).getAsJsonArray();
Lưu ý
- JSON-lib **deprecated**, nhiều dependency, không còn cập nhật.
- Jackson/Gson: serialize Collection/List/Set trực tiếp, không cần JSONArray trung gian.
- Jackson
TypeReferencecho deserialize generic collection:mapper.readValue(json, new TypeReference<List<String>>(){}).