简体   繁体   English

Spring Boot API响应(application / json)转换为响应(text / xml)

[英]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 ?? 在用例上工作,Springboot Microservice接受JSON负载,然后在@RestController处理程序中,API将触发另一个下游应用程序,该应用程序接受application/xmltext/xml负载。

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

Using RestTemplate and HTTPEntity to represent Request and Response entity. 使用RestTemplate和HTTPEntity表示请求和响应实体。

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. 如果我使用@XmlRootElement批注,则错误是:无法实例化类的JAXBContext。

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 客户端---- json ---->服务器1 -------- Xml ------ > Server2

Client <---- json ---- Server 1 <-------- Xml ------- Server2 客户端<---- json ----服务器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. 您可以将JSON数据接受到Java模型中,现在您必须使用XML作为输入来访问另一个Web服务。 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. 将此XML传递到webservice,它将返回您的XML。 UNmarshall it again into it's response object and return as JSON using Spring Boot Webservice. 再次将其编组到其响应对象中,并使用Spring Boot Webservice作为JSON返回。

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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