Qurakus Serialize "primitives" in RestClient

488 views Asked by At

I am struggling with the Quarkus RestClient.

First create a Controller that simply print our request body: e.G.

    @Path("/test")
    public class ExampleController {
        @PUT
        public void test(String data) {
            System.out.println(data);
        }
    }

Now we create a RestClient that accepts any Object as the request body:

    @RegisterRestClient(baseUri = "http://localhost:8081/test")
    public interface RestClientExample {
        @PUT
        @Produces(MediaType.APPLICATION_JSON)
        @Consumes(MediaType.APPLICATION_JSON)
        void put(Object data);
    }

Pleas notice that we say @Consumes(MediaType.APPLICATION_JSON) so the body should JSON serialized during the request.

Do a quick test:

    @QuarkusTest
    class TestPrimitives {
        @Inject
        @RestClient
        RestClientExample example;
        @Test
        void test() {
            example.put("hello\nworld");
            example.put(new TestRequest());
        }
        public static class TestRequest {
            private String data = "hello\nworld";
            public String getData() {
                return data;
            }
        }
    }

You will see:

hello
world
{"data":"hello\nworld"}

If you send any type of Objects that are no primitves, the body will be respresented as JSON. If you send a String the body is not JSON serialized (the linebreak should be a \n like in the second request). Unfortently I need also the Strings serialized. How can i achive that?

Update

so that I can be better understood: Replace the Controller with: So we do the JSON parsing.

@PUT
    @Consumes(MediaType.APPLICATION_JSON)
    public void test(String data) {
        System.out.println(Json.createReader(new StringReader(data)).readValue());
    }

This will fail:

Caused by: javax.json.stream.JsonParsingException: Unexpected char 104 at (line no=1, column no=1, offset=0)
    at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:577)
1

There are 1 answers

5
loicmathieu On

Unfortunatly, you tell your rest client to send JSON and a String is a valid JSON Object, so your result is logical.

As you logged the String using System.out, the \n character is displayed as a line break.

For me there is nothing wrong on this code and it works as it should work.

If you relly want your \n to not be evaluated as a line break, you need to escape the \ from you call site (the rest client code is OK)

@QuarkusTest
class TestPrimitives {
    @Inject
    @RestClient
    RestClientExample example;
    @Test
    void test() {
        example.put("hello\\nworld");
        example.put(new TestRequest());
    }
    public static class TestRequest {
        private String data = "hello\nworld";
        public String getData() {
            return data;
        }
    }
}