Search code examples
springresttemplatejson

Spring rest client + camunda rest api: postForObject only accept camunda.bpm JSONObject but JacksonMessageConverter only takes javax JsonObject


I'm trying to build a rest client with Springframework's RestTemplate but the problem is that my api is Camunda Rest Api.

That means that I can only send Camunda.bpm's JSONObject type through postForObject but my JacksonJsonConverter only parses javax's JsonObject.

I'm getting either the

no message converter found for the request type camunda JSONObject

or the

bad media type exception when I use JSONObject type and JsonObject type respectively.

New to spring and been stuck for several days, anyone can help?


Solution

  • After some research on how MappingJackson2HttpMessageConverter actually works and taking a closer look at Camunda REST API's request content format, I found that the problem lies in Jackson converter not able to parse anything that doesn't starts with the ArrayList start token "[". Since I have to pass a request with the start token "{" as requested by Camunda, I wrote my own Jackson converter. Specifically, I override the readJavaType() method in Jackson2:

    private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
            try {
    
                String parseInput = "["+convertStreamToString(inputMessage.getBody())+"]";
                InputStream stream = new ByteArrayInputStream(parseInput.getBytes(StandardCharsets.UTF_8));
                return this.objectMapper.readValue(stream, javaType);
            }
            catch (IOException ex) {
                throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
            }
        }