【问题标题】:Spring boot API response(application/json) convert to response (text/xml)Spring Boot API 响应(应用程序/json)转换为响应(文本/xml)
【发布时间】:2018-06-02 00:21:34
【问题描述】:

处理用例,Springboot 微服务接受 JSON 有效负载,然后,在 @RestController 的处理程序中,API 将触发另一个下游应用程序应用程序,该应用程序接受 application/xmltext/xml 中的有效负载??

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

使用 RestTemplate 和 HTTPEntity 来表示 Request 和 Response 实体。

现在面临以下错误:

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.

如果我使用@XmlRootElement 注释,那么错误是:无法为类实例化 JAXBContext。

还有什么建议我怎样才能实现这个功能?

【问题讨论】:

  • 请发布您的代码
  • 对不起@AlexSavitsky,我不能分享这个工作场所代码,但会在使用虚拟逻辑复制业务逻辑后发布。

标签: java spring rest spring-boot microservices


【解决方案1】:

根据您的问题,您必须实现以下流程:

客户端 ----json----> 服务器 1 --------Xml ---- ---> Server2

客户端 json---- 服务器 1 Xml ------- Server2


您可以将 JSON 数据接收到 Java 模型中,现在您必须使用 XML 作为输入来访问另一个 Web 服务。以下是可以帮助您实现它的方法:

    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;
}

将此 XML 传递给 Web 服务,它将返回 XML。再次将其解组到它的响应对象中,并使用 Spring Boot Webservice 作为 JSON 返回。

Reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多