如何使用Java中的JSON-lib API将集合转换为JSON数组?

import java.util.*; import net.sf.json.JSONArray; import net.sf.json.JSONSerializer; public class ConvertCollectionToJsonArrayTest { public static void main(String[] args) { List strList = Arrays.asList("India", "Australia", "England", "South Africa"); JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(strList); System.out.println(jsonArray.toString(3)); //pretty print JSON List objList = new ArrayList(); objList.add("List Data"); objList.add(new Integer(50)); objList.add(new Long(99)); objList.add(new Double(50.65)); objList.add(true); objList.add(new char[] {'X', 'Y', 'Z'}); jsonArray = (JSONArray)JSONSerializer.toJSON(objList); System.out.println(jsonArray.toString(3)); //pretty print JSON } }

输出

[
   "India",
   "Australia",
   "England",
   "South Africa"
]
[
   "List Data",
   50,
   99,
   50.65,
   true,
      [
      "X",
      "Y",
      "Z"
   ]
]

以上就是如何使用Java中的JSON-lib API将集合转换为JSON数组?的详细内容,更多请关注其它相关文章!