簡體   English   中英

Spring Boot API響應(application / json)轉換為響應(text / xml)

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

在用例上工作,Springboot Microservice接受JSON負載,然后在@RestController處理程序中,API將觸發另一個下游應用程序,該應用程序接受application/xmltext/xml負載。

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

使用RestTemplate和HTTPEntity表示請求和響應實體。

現在面臨以下錯誤:

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。

還有任何建議我如何實現此功能?

根據您的問題,您必須實現以下流程:

客戶端---- 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傳遞到webservice,它將返回您的XML。 再次將其編組到其響應對象中,並使用Spring Boot Webservice作為JSON返回。

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM