'how to serialize String/null as json in quarkus?

quarkus serialize String as plain string, null as empty body(with http code 204)

"foo" -> foo

null -> (empty body)

how to make it serialize String and null as json like:

"foo" -> "foo"

null -> null



Solution 1:[1]

You could try somhthing like this:

package org.acme.config;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/greeting")
public class GreetingResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String greetirng() {
        return "{\"greeting\": \"Hello, JSON\", \"penalty\": null}";
    }
        
}

Check it:

$ curl localhost:8080/greeting
{"greeting": "Hello, JSON", "penalty": null}

Solution 2:[2]

You should use the ObjectMapper class for serializing/deserialising process in Quarkus.

ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects)

First, you must be sure the io.quarkus:quarkus-jackson package exists in your build.gradle file. If it doesn't exist you can install it with this command:

./gradlew addExtension --extensions="io.quarkus:quarkus-jackson"

After that, you must get an instance: ObjectMapper objectMapper = new ObjectMapper();

You will find your need in this instance of ObjectMapper.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S. Kadakov
Solution 2 Salih KARAHAN