Real-World JSON Examples
User Profile Management
public class UserProfileExample {
public static void main(String[] args) {
JSONArray users = new JSONArray();
JSONObject user1 = new JSONObject();
user1.put("id", 1);
user1.put("name", "Alice Johnson");
user1.put("email", "[email protected]");
user1.put("skills", new JSONArray().put("Java").put("Python"));
users.put(user1);
System.out.println(users.toString(2));
}
}
E-Commerce Product Catalog
public class ProductCatalogExample {
public static void main(String[] args) {
JSONArray products = new JSONArray();
JSONObject product1 = new JSONObject();
product1.put("id", "P001");
product1.put("name", "Laptop");
product1.put("price", 999.99);
product1.put("categories", new JSONArray().put("Electronics").put("Computers"));
products.put(product1);
System.out.println(products.toString(2));
}
}
Data Processing Workflow
graph TD
A[JSON Data Input] --> B[Parsing]
B --> C[Transformation]
C --> D[Validation]
D --> E[Storage/Output]
API Response Handling
public class APIResponseExample {
public static void processAPIResponse(String jsonResponse) {
try {
JSONObject response = new JSONObject(jsonResponse);
JSONArray data = response.getJSONArray("results");
for (int i = 0; i < data.length(); i++) {
JSONObject item = data.getJSONObject(i);
System.out.println("Processing: " + item.getString("name"));
}
} catch (JSONException e) {
System.err.println("Error processing response: " + e.getMessage());
}
}
}
JSON Array Use Cases
Scenario |
JSON Array Application |
Key Benefits |
Configuration |
Store application settings |
Flexible, human-readable |
Data Exchange |
API responses |
Lightweight, universal |
Logging |
Store event records |
Easy serialization |
Caching |
Temporary data storage |
Quick access, simple structure |
Complex Nested JSON Example
public class NestedJSONExample {
public static void main(String[] args) {
JSONArray organizations = new JSONArray();
JSONObject org = new JSONObject();
org.put("name", "Tech Innovations");
JSONArray departments = new JSONArray();
JSONObject dept1 = new JSONObject();
dept1.put("name", "Engineering");
dept1.put("employees", new JSONArray().put("John").put("Sarah"));
departments.put(dept1);
org.put("departments", departments);
organizations.put(org);
System.out.println(organizations.toString(2));
}
}
- Use efficient JSON libraries
- Minimize object creation
- Implement lazy loading
- Cache parsed JSON structures
By exploring these real-world examples, developers can leverage LabEx's comprehensive learning resources to master JSON array manipulation in Java applications.