StFS
StFS

Reputation: 1722

Include class name (Kotlin data class) in JSON response in Quarkus

I'm new to Quarkus and Kotlin and truth be told, I'm not quite sure yet what goes on behind the scenes and which JSON library is actually responsible for rendering the JSON response from a resource when I set the @Produces(MediaType.APPLICATION_JSON) on my function. But I'm returning an instance of a data class that I created from that method and all of the fields in that data class are rendered in the response. However, I have multiple response classes and I would like to include the name of the class in the JSON response. What I have now is a String field that is simply hard coded to the name of the class but that is ugly as I have to repeat the class name:

data class StuffInitiatedResponse (
    val id: String,
    val projectId: String
) {
    val operation = "StuffInitiatedResponse"
}

data class StuffCompletedResponse (
    val id: String,
    val projectId: String,
) {
    val operation = "StuffCompletedResponse"
}

And in my service class:

@Path("/myservice")
class MyService {

    @POST
    @Path("{project}/{path:.*}")
    @Produces(MediaType.APPLICATION_JSON)
    fun initiateStuff(@PathParam project: String,
                      @PathParam path: String,
                      @QueryParam("completedId") completedId: String?) : StuffInitiatedResponse {
        
        if (completedId == null) {
            println("I've initiated stuff")
            return StuffInitiatedResponse(UUID.randomUUID().toString(), project)
        } else {
            println("I've completed stuff")
            return StuffCompletedResponse(completedId, project)
        }
    }
}

This produces what I expect but as I said, I'm annoyed that I have to repeat the class name in the "response" field of the data classes. Is there some way for me to have the class name embedded in the JSON?

Upvotes: 0

Views: 450

Answers (1)

Guillaume Smet
Guillaume Smet

Reputation: 10539

The JSON library depends on the dependencies you defined. It can be either Jackson or Yasson.

I recommend using Jackson and, in this case, you can use the @JsonTypeInfo annotation on your serialized classes, which has some options to include the type in the JSON output.

Upvotes: 1

Related Questions