For many of my projects I like to use the org.jsonschema2pojo.jsonschema2pojo-maven-plugin
maven plugin in order to generate some POJO class from a json schema file. This works great and saves me from writing boiler plate code.
However, I often treat these classes as final and immutable so I would like the ability to generate Java records instead so I can enforce those restrictions and get the performance enhancement that comes along with records. I've gone through the documentation and the GitLab repo but I don't see any way to do this with this particular plugin.
Is there something I've missed or is there another plugin or library that offers this ability?
Edit: Assume I've done my research and Java records are in fact what I want/need. I don't want mutability, I don't want extendability, I'm okay with exposing member fields, I want improved performance on comparison operations (.equals), and I want to leverage pattern matching.
I would avoid records, not only because they should only store a few values, but because they do not have the same level of control as a traditional class.
The following article breaks this all down:
With Jackson's
@JsonProperty
annotation, you can tell the serializer/deserializer how to map each key to the appropriate field.If you generate the class stubs and add in some Lombok, you can simplify this process.
The following JSON:
Get converted to the following shapes:
I generated the code above using the following tool:
I added Lombok
@Data
annotations, made all fieldsprivate
, and modified fields where noted.Jackson + Records Caveat
Please note that Jackson versions below 2.11.4 have trouble with deserializing JSON with records:
The following modified program (from above) uses records instead of classes mized with Lombok. It no longer depends on Lombok.
If you encounter the following exception, you will need to update your Jackson dependency: