Getting JAXBElement objects from another REST API service via Rest Template

318 Views Asked by At

I have two REST APIs, one of them is returning response objects which are generated by xsd file and the other is requesting for that object.

Example of generated class:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AlternateNumberEntry21", propOrder = {
    "phoneNumber",
    "extension",
    "ringPattern",
    "description"
})
public class AlternateNumberEntry21 {

   @XmlElementRef(name = "phoneNumber", type = JAXBElement.class, required = false)
   protected JAXBElement<String> phoneNumber;

   @XmlElementRef(name = "extension", type = JAXBElement.class, required = false)
   protected JAXBElement<String> extension;

   @XmlElementRef(name = "ringPattern", type = JAXBElement.class, required = false)
   protected JAXBElement<RingPattern> ringPattern;

   @XmlElementRef(name = "description", type = JAXBElement.class, required = false)
   protected JAXBElement<String> description;
}

The second API is invoking endpoints from first API via RestTemplate.

  restTemplate.exchange(url, HttpMethod.GET, entity, AlternateNumberEntry21.class);

And the controller's method of first API which returning generated objects:

@GetMapping("/alternate-numbers")
public ResponseEntity<AlternateNumberEntry21> getAlternateNumbers(@PathVariable String userId)  {
    return ResponseEntity.ok(incomingCallService.getAlternateNumbers(userId));
}

Unfortunately I'm getting this error:

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class javax.xml.bind.JAXBElement]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `javax.xml.bind.JAXBElement` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

I tried to make custom ObjectMapper with JAXBElement mixin but it doesn't help.

@Configuration
public class CoreConfig {
    
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.addMixIn(JAXBElement.class, JAXBElementMixIn.class);
        return objectMapper;
    }
}




@Slf4j
public abstract class JAXBElementMixIn<T> {

    @JsonCreator
    public JAXBElementMixIn(@JsonProperty("name") QName name,
                            @JsonProperty("declaredType") Class<T> declaredType,
                            @JsonProperty("scope") Class scope,
                            @JsonProperty("value") T value) {
        log.debug("name {} value {}", name, value);
    }
}

Is there a way to deserialize it correctly to the same type class?

0

There are 0 best solutions below