Skip to content
Advertisement

Spring RestTemplate: how to send the payload body as compact form so without rn

I am dealing with an API that don’t accept multi line json body and accept only 1 json line body (json compact form)

The below payload is valid because it’s compact in just 1 line working

And the below payload is not passing because it’s multiline

Not working

I have the same problem in the Java/Spring code where I got this error while posting my object in restemplate.

Is there a way to convert the payload body into 1 single json line?

Code I am using to post the payload via RestTemplate

private HttpHeaders headers() {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN));
        return headers;
}

post(ParameterizedTypeReference type, REQUEST myObject, URI uri) {
        HttpEntity<REQUEST> entity = new HttpEntity<>(myObject, headers());
        ResponseEntity<String> res = restTemplate.exchange(uri, HttpMethod.POST, entity , type);
}

Advertisement

Answer

The solution that worked for me is to annotate my request class with a custom JsonSerializer

This MyRequestClassSerializer#serialize will be called once restTemplate.exchange(uri, HttpMethod.POST, entity , type); is executed

Hence the payload will be compacted in 1 line by using JsonGenerator#writeRawValue

public class MyRequestClassSerializer extends JsonSerializer<MyRequestClass> {

    @Override
    public void serialize(MyRequestClass value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
        jsonGenerator.writeStartObject();

        ObjectMapper mapper = ((ObjectMapper) jsonGenerator.getCodec());
        jsonGenerator.writeFieldName("FieldName");
        String stringValue = mapper.writeValueAsString(value);
        jsonGenerator.writeRawValue(stringValue);

        jsonGenerator.writeEndObject();
    }

}
@JsonSerialize(using = MyRequestClassSerializer.class)
public class MyRequestClass{
   ...
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement