'Records and JSON marshalling on endpoint does not work
I have this record:
public record WordFrequencyImpl(String word, int frequency) implements WordFrequency { }
and a JakartaEE project (pom.xml)
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>9.1.0</version>
<scope>provided</scope>
</dependency>
This is my REST (JSON) endpoint
@POST
@Path("calculate_frequency/number/{word}")
@Produces(MediaType.APPLICATION_JSON)
public Response mostFrequentNWords(@PathParam("word") int number, String txt) {
final List<WordFrequency> entity = this.wordFrequencyAnalyzer.calculateMostFrequentNWords(txt, number);
return Response.ok(entity).build();
}
First I had a POJO instead of a record for the WordFrequencyImpl, the endpoint produced nice JSON like,
###
GET http://localhost:8080/wordcounter/rest/analyse/calculate_frequency/number/5
Accept: application/json
[
{
"frequency": 5,
"word": "the"
},
{
"frequency": 2,
"word": "coffee"
},
{
"frequency": 2,
"word": "ok"
},
{
"frequency": 2,
"word": "we"
},
{
"frequency": 1,
"word": "about"
}
]
Now I changed it to a Java record and I get empty JSON because the marshalling fails as the record does not have the same getter accessor types.
[
{},
{},
{},
{},
{}
]
Is there a way I can still use the record and have the endpoint produce the nice JSON again or isn't it supported yet? The marshaling in this case is Jakarta "magic". I do not directly control it. So how to solve?
I use Java 17 / Payara server full.
I saw this blog by Adam Bien (https://adambien.blog/roller/abien/entry/serializing_and_deserializing_java_records) where he does this in a test, but I don't know how to translate this to the REST (JSON) endpoint.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
