From JSONObjects to POJOs: Cleaning Up Java APIs

From JSONObjects to POJOs: Cleaning Up Java APIs

When building backend services in Java, it’s tempting to use JSONObject to handle incoming request payloads. It’s flexible, quick to implement, and lets you skip writing model classes.

I’ve done it myself, especially when building early-stage prototypes or working in legacy systems where JSONObject was already in use. At that stage, avoiding boilerplate feels like a time-saver.

But over time, the trade-offs start to add up.

The Hidden Costs of JSONObject

In a trade API I worked on, requests came in as JSON with fields like symbol, side, price, and timestamp. The controller would parse the raw payload using JSONObject, like this:

String symbol = jsonObject.getString("symbol");
double price = jsonObject.getDouble("price");        

This worked for a while until it didn’t.

Here are the issues I ran into:

1. Type Mismatches

JSONObject doesn’t enforce types. If a client sends "price": "twenty" instead of a number, you don’t find out until runtime. And if the field is missing or null, it either throws an exception or silently returns a default.

When dealing with something like financial trades, the cost of bad data isn’t just technical, it could be financial or legal.

2. Field Access That Silently Fails

Methods like optDouble() and optString() don’t throw errors. They just return default values (0.0, "", etc.) if a field is missing or malformed.

That means a malformed request can sneak through your logic without raising alarms. In our case, if a field like "side" was left out, the system would treat it as "NONE" and proceed. That’s not something you want happening in a trade execution system.

3. Fragile Unit Tests

Testing with JSONObject usually means hand-writing JSON strings or manually building objects with loosely typed keys. This leads to tests that don’t fail when something actually breaks.

When I switched to typed request models, test coverage improved. The compiler helped surface missing fields. Refactors became safer. Tests started validating actual logic, not string formatting.

The Shift: Moving to Typed POJOs

Eventually, I created a TradeRequest Java class to represent the expected input.

public class TradeRequest {
    private String symbol;
    private double price;
    private int quantity;
    private String side;
    private String tradeTimestamp;
    // Getters and setters
}        

In the controller, I switched to:

@PostMapping
public TradeResponse handleTrade(@RequestBody TradeRequest request) {
    
}        

This change brought immediate clarity:

(1) I could reason about the structure of my input.

(2) Spring could automatically deserialize the JSON into my model.

(3) I no longer needed to check every field for nulls manually.

(4) The request/response structure became part of the API contract.

Why POJOs Matter

POJO stands for Plain Old Java Object, a term coined in the early 2000s as a reaction to the overly complex object hierarchies in Java frameworks at the time. POJOs are simple classes without special rules or framework dependencies.

They made Java code easier to test, easier to read, and easier to reuse.

Frameworks like Spring, Hibernate, and Jackson helped popularize POJOs by designing around them. In Spring Boot, most of your code: controllers, service classes, domain models, is already POJO-based.

The point is: structure improves quality. It reduces room for error, supports better documentation, and integrates cleanly with tools like validation, Swagger/OpenAPI, and serialization libraries.

Try It Yourself

I open-sourced a side-by-side demo showing both approaches: github.com/edilchristian/json-vs-pojo-trade-demo

It’s a small Spring Boot project with two endpoints:

  • /trade/dynamic uses JSONObject
  • /trade/typed uses a typed TradeRequest POJO

You can see for yourself how the code structure and behavior change when you move to POJOs.

Takeaways

JSONObject is useful for quick scripts or throwaway prototypes. But if you're building a real API, especially one that processes structured data like trades, orders, users, or reports, POJOs are the way to go.

They’re not just about writing more classes. They’re about writing safer, more predictable, and more maintainable systems.

#Java #SpringBoot #BackendEngineering #SoftwareDesign #FinTech #APIBestPractices #POJO


To view or add a comment, sign in

Others also viewed

Explore content categories