When working with JSON in Java, developers may encounter issues like java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntime, often due to missing dependencies. For example, the net.sf.json library requires several JAR files: commons-beanutils-1.9.1.jar, commons-collections-3.2.1.jar, commons-lang-2.6.jar, commons-logging-1.2.jar, and ezmorph-1.0.6.jar. Managing these dependencies can be cumbersome, and commons-lang has not been updated since 2011, making it less maintainable.
Modern alternatives like Google's Gson, Alibaba's FastJSON, and Jackson offer better maintenance and features. Jackson excels at JSON-object mapping but can be complex for simple use cases. FastJSON provides convenient static methods, while Gson is a balanced option. Given these factors, it's advisable to avoid net.sf.json and standardize on a single JSON library per project, such as FastJSON or Gson.
For converting a list of objects to a JSON array, FastJSON simplifies the process. Below is an example using FastJSON to generate a formatted JSON array from a list of maps:
package study.base.json.fastjson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class JsonExample {
public static void main(String[] args) {
List<map object="">> dataList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Map<string object=""> entry = new HashMap<>();
entry.put("id", i);
entry.put("age", 12);
entry.put("username", "luzhifei");
dataList.add(entry);
}
JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(dataList));
System.out.println(jsonArray.toString(SerializerFeature.PrettyFormat));
}
}</string></map>
The output will be a formatted JSON array:
[
{
"username": "luzhifei",
"id": 0,
"age": 12
},
{
"username": "luzhifei",
"id": 1,
"age": 12
},
{
"username": "luzhifei",
"id": 2,
"age": 12
}
]