Keywords: Java | JSON Conversion | List Serialization | Gson Library | JSONObject
Abstract: This article provides an in-depth exploration of multiple methods for converting List collections to JSON format in Java, with a focus on manual construction using JSONObject and JSONArray, as well as simplified approaches using the Gson library. Through comprehensive code examples, it demonstrates how to properly handle type conversion errors and delves into the core principles of JSON serialization. The content covers key technical aspects including data structure mapping, type handling, and performance optimization, offering developers a complete solution for JSON conversion.
Technical Implementation of Java List to JSON Conversion
In Java development, converting collection data to JSON format is a common requirement. Based on practical development scenarios, this article provides an in-depth analysis of how to correctly convert List<Product> type data to JSON format and resolve common type conversion issues.
Problem Analysis and Error Causes
The type mismatch error in the original code stems from inconsistency between the method signature and return type. The method declares a return type of List<Product> but actually returns a String type JSON string. This type inconsistency causes compilation errors and requires redesigning the method structure.
JSONObject Manual Construction Solution
Using JSONObject and JSONArray classes allows precise control over JSON structure. Here is the complete implementation:
public static String getCartListAsJson() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", p.getId());
formDetailsJson.put("name", p.getName());
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);
return responseDetailsJson.toString();
}The JSON string returned by this method has the following format:
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}Gson Library Simplified Solution
Google's Gson library provides a more concise serialization approach:
public static String getCartListAsJsonWithGson() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
Gson gson = new Gson();
String jsonCartList = gson.toJson(cartList);
System.out.println("jsonCartList: " + jsonCartList);
return jsonCartList;
}Gson automatically serializes the entire list into JSON array format without manual construction of each object.
JSON Deserialization Processing
Restoring Java objects from JSON strings is equally important:
// Using Gson for deserialization
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
System.out.println("prodList: " + prodList);Practical Application Scenario Extension
Referencing the ACS Commons Generic List conversion case, JSON conversion is commonly used in web development for frontend-backend data interaction:
@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class GenListConverterImpl implements GenListConverter {
@SlingObject ResourceResolver resourceResolver;
@Inject @Default(values = "/etc/acs-commons/lists/targets")
private String genericListPath;
private String genericListJson;
@PostConstruct
protected void init(){
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
Page listPage = pageManager.getPage(genericListPath);
GenericList genericList = listPage.adaptTo(GenericList.class);
Gson gson = new Gson();
genericListJson = gson.toJson(genericList);
}
@Override
public String getGenericListInJson() {
return genericListJson;
}
}Performance Optimization and Best Practices
When handling large-scale data, the following optimization strategies are recommended: use StringBuilder to construct JSON strings, avoid frequent object creation; implement custom serializers for complex object structures; properly handle circular references and null values.
Error Handling and Exception Management
In practical applications, it's essential to properly handle exceptions during JSON conversion, including data format errors, type conversion exceptions, and null pointer exceptions. It's recommended to wrap conversion logic in try-catch blocks and provide meaningful error messages.