Generating Java record classes with Jackson Annotations to map JSON using ChatGPT

There’s a lot of discussion about how to use ChatGPT to generate tests for code. Another interesting use case I’ve seen fairly little coverage of is generating DTOs from JSON. Here is an example with the prompt I’ve put together applied to JSON from the manifest of a Distributed Map Run.

Please generate a Java record class with Jackson annotations to represent the following JSON. Prefer List objects to arrays. Use Long values to represent integer values. Use Double to represent floating-point values. Use nested records for any helper types, not multiple top-level classes. Do not provide mappings for any empty object or array fields.

{
  "DestinationBucket": "my-bucket-name",
  "MapRunArn": "arn:aws:states:us-east-2:123456789012:mapRun:MyStateMachine/Map:4977ded7-b097-3bee-81e1-7863c5660f29",
  "ResultFiles": {
    "FAILED": [],
    "PENDING": [],
    "SUCCEEDED": [
      {
        "Key": "garbage/4977ded7-b097-3bee-81e1-7863c5660f29/SUCCEEDED_0.json",
        "Size": 2328
      }
    ]
  }
}

This was ChatGPT 4o model’s response:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;

@JsonInclude(JsonInclude.Include.NON_NULL)
public record JsonResponse(
    @JsonProperty("DestinationBucket") String destinationBucket,
    @JsonProperty("MapRunArn") String mapRunArn,
    @JsonProperty("ResultFiles") ResultFiles resultFiles
) {
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public record ResultFiles(
        @JsonProperty("SUCCEEDED") List<SucceededFile> succeeded
    ) {}

    @JsonInclude(JsonInclude.Include.NON_NULL)
    public record SucceededFile(
        @JsonProperty("Key") String key,
        @JsonProperty("Size") Long size
    ) {}
}

As a rule, the output is quite good, as it is here. Some parts of the code generate are inconsistent — for example, sometimes it uses @JsonInclude and sometimes it doesn’t — but the code isn’t always exactly right, but so far it has always saved me time.

To the extent that people are disappointed with ChatGPT or generative AI in general, I think it’s because they expected something more like AGI and less like a (very) sophisticated autocomplete. For my part, I continue to be very impressed. ChatGPT is an enormous time saver in my day-to-day coding activities.

Leave a Reply

Your email address will not be published. Required fields are marked *