简体   繁体   中英

Spring boot API response(application/json) convert to response (text/xml)

Working on use case,A Springboot Microservice accepts JSON payload and then , in handler of the @RestController , the API will trigger another downstream application application which accepts payload in either application/xml or text/xml ??

/api/v1/users Type:application/JSON ---> /api/v1/downstream/ Type: text/xml

Using RestTemplate and HTTPEntity to represent Request and Response entity.

Right now facing the below errors :

Could not extract response: no suitable HttpMessageConverter found for response type (How could I register new message converters), please bare with me I'm new to Spring boot and Spring.

If I use @XmlRootElement annotation, then the error was : Could not instantiate JAXBContext for class.

Also any suggestions how can I acheive this functionality ??

According to your questions you have to achieve following flow :

Client ---- json - ---> Server 1 -------- Xml ----- --> Server2

Client <---- json ---- Server 1 <-------- Xml ------- Server2


You are able to accept JSON data into Java Models and now you have to hit another webservice with XML as your input. Below is method which can help you to achive it :

    private static String jaxbObjectToXML(Customer customer) {
    String xmlString = "";
    try {
        JAXBContext context = JAXBContext.newInstance(Customer.class);
        Marshaller m = context.createMarshaller();

        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML

        StringWriter sw = new StringWriter();
        m.marshal(customer, sw);
        xmlString = sw.toString();

    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return xmlString;
}

Pass this XML to webservice and it will return you XML. UNmarshall it again into it's response object and return as JSON using Spring Boot Webservice.

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM