Skip to content

Code Generator

The JsonCodeGenerator is a massive timesaver. It natively reverse-engineers arbitrary JSON trees (e.g., big API responses) and writes Java Record code that matches the structure exactly.

You no longer need to jump to an external website to stub out your DTOs!

Generating Java Records

java
import io.github.dhoondlayai.artifact.json.codegen.JsonCodeGenerator;
import io.github.dhoondlayai.artifact.json.streaming.FastJsonEngine;
import io.github.dhoondlayai.artifact.json.model.JsonNode;

String json = """
{
  "status": 200,
  "data": {
    "user_id": 101,
    "user_name": "Alice",
    "permissions": ["READ", "WRITE"],
    "preferences": {
      "dark_mode": true
    }
  }
}
""";

JsonNode root = FastJsonEngine.parse(json);

// The first arg is the name of the top-level record to generate
String sourceCode = JsonCodeGenerator.generateJavaRecords("ApiResponse", root);
System.out.println(sourceCode);

Output Result:

java
// ⚡ Auto-generated by artifact-json

public record Preferences (
    boolean darkMode
) {}

public record Data (
    int userId,
    String userName,
    java.util.List<String> permissions,
    Preferences preferences
) {}

public record ApiResponse (
    int status,
    Data data
) {}

How It Works

  1. Type Inference: Decides between String, int, double, boolean, and Object.
  2. Case Conversion: Automatically unwraps snake_case keys in the JSON to create camelCase Java properties (e.g. user_iduserId).
  3. Array Items: Infers the list type from the first element of the array. If the first element is an object, it creates a new record matching ClassNameItem. Let's say you have an array users, it'll create a UsersItem inner record!
  4. Deduplication: Deeply nested records are properly hoisted to the file's root so you can just copy-paste everything into a .java file.

Released under the MIT License.