Chuyển Java array (Object[]) thành JSONArray dùng JSONSerializer.toJSON().
Ví dụ minh họa
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
public class ArrayToJsonArrayTest {
public static void main(String[] args) {
Object[] objArray = new Object[] {
"Array to JSON Array",
new Integer(10),
new Long(30),
new Double(14.26),
true,
new char[] {'X', 'Y', 'Z'}
};
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(objArray);
System.out.println(jsonArray.toString(3)); // pretty print
}
}
Output
[
"Array to JSON Array",
10,
30,
14.26,
true,
[ "X", "Y", "Z" ]
]
Giải thích
JSONSerializer.toJSON(Object)tự detect type: Collection→JSONArray, Map→JSONObject, Array→JSONArray, Bean→JSONObject, primitive→value.- Char array
char[]chuyển thành JSONArray các string single-char. - Primitive array (
int[],double[]) **không** tự convert → cần wrapper array hoặc List.
Alternative: Jackson (Khuyến nghị)
ObjectMapper mapper = new ObjectMapper();
// Object[] → JSON string
String json = mapper.writeValueAsString(objArray);
// Object[] → JsonNode (tree model)
JsonNode node = mapper.valueToTree(objArray);
JsonNode first = node.get(0); // "Array to JSON Array"
Alternative: Gson
Gson gson = new Gson();
String json = gson.toJson(objArray);
// JsonArray jsonArray = gson.toJsonTree(objArray).getAsJsonArray();
Lưu ý
- JSON-lib **unmaintained**. Dùng Jackson/Gson cho dự án mới.
- Primitive array (
int[]) cần convert sangInteger[]hoặc List trước khi serialize với JSON-lib. - Jackson/Gson handle primitive array tự động.