Explain Codes LogoExplain Codes Logo

How to fluently build JSON in Java?

java
json-engineering
object-mapping
builders
Anton ShumikhinbyAnton Shumikhin·Oct 6, 2024
TLDR

Effortlessly create JSON in Java by harnessing the power of Jackson's ObjectMapper and ObjectNode. This killer combo enables method chaining for an intuitive approach to JSON assembly:

ObjectMapper mapper = new ObjectMapper(); ObjectNode json = mapper.createObjectNode() .put("name", "John Doe") .put("age", 30) .set("contact", mapper.createObjectNode() .put("email", "[email protected]") // I see, you only communicate by email .put("phone", "123-456-7890")); // And landline, how vintage! String jsonString = mapper.writeValueAsString(json); System.out.println(jsonString); // Ta-da! JSON at its best.

In three simple steps, we create a nested JSON structure with fluent syntax and convert it to string.

Fast, flexible, functional: JsonNode

When needing flexible construction and manipulation of JSON, Jackson's JsonNode and ObjectNode offer dynamic, runtime construction of JSON trees:

ObjectNode json = mapper.createObjectNode(); json.put("user", "coder123") // Don't tell me your password, .putObject("preferences") // Here's where you keep all your dark secrets .put("language", "Java") // Coffee or Computation? Both. .put("theme", "Dark"); // Saving power, one pixel at a time. json.withArray("achievements") // Let's add a sprinkle of achievements .add("Completed 1000 SO answers") // Gotta flex 'em answers .add("Authored top-voted Java answer"); // Not quite there yet, but we're getting there String output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); System.out.println(output); // .... And print

Less fuss with Lombok and Jackson

In the modern times of fast-paced coding, Lombok's annotations streamline serialization to JSON, reducing boilerplate and simplifying DTOs creation:

@Data @JsonInclude(JsonInclude.Include.NON_NULL) public class User { private String name; private int age; private Contact contact; } ObjectMapper mapper = new ObjectMapper(); User user = new User(); user.setName("John Doe"); user.setAge(30); user.setContact(new Contact("[email protected]", "123-456-7890")); String jsonString = mapper.writeValueAsString(user); System.out.println(jsonString);

The beauty of simplicity: org.json

For straightforward JSON creation with lesser dependencies, try the org.json library:

JSONObject json = new JSONObject() .put("username", "devGenius") .put("score", 99) .put("details", new JSONObject() .put("streak", "5 days") .put("location", "StackOverflow")); System.out.println(json); // And there's your JSON!

Building blocks to maintainability

Simplify, then add lightness

While building JSON, aim for simplicity and efficiency. Apply straightforward patterns with readily available functionalities like Java EE's JsonObjectBuilder and avoid over-complicating things.

Handle complexity with grace

When handling complex JSON, libraries like fluent-json offer type safety, making it difficult to introduce bugs with chained calls for a readable and maintainable style:

JsonBuilder jsonBuilder = new JsonBuilder() .addObject("user", new JsonBuilder() .add("id", 1) .add("name", "stackOverflower")); System.out.println(jsonBuilder.build()); // Here's a simple, yet complex JSON

Choose wisely

Assess your project's JSON needs against libraries' features. Libraries embracing Java 8 features and object mapping capabilities can future-proof your code.

Utilizing builders and factories

Embrace structured creation

Use builders and factories found in libraries like Gson or MongoDB's BSON for a fluent interface and comprehensive JSON structures.

Array within an object? Easy-Peasy!

Handle JSON situations involving nested arrays within objects using array builders for a neat insertion without breaking the flow:

JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); arrayBuilder.add("Item 1") .add("Item 2") .add("Item 3"); objectBuilder.add("items", arrayBuilder); // This is where the magic happens String jsonString = objectBuilder.build().toString(); System.out.println(jsonString); // And, done!

Managing types like a pro

Check if your chosen library supports handling various data types like Booleans, numbers, strings, or even raw JSON objects and arrays.