[英]Convert Java JAXB object to JSON using Jackson or MOXy dependency
我正在開發一個API,該API將從XML源返回JSON響應。 我已經使用RestTemplate
和JAXB
從源中獲取XML字符串,然后使用StringReader
和Unmarshaller
創建Java對象。 對象看起來像這樣;
@XmlRootElement(name="ItemSearchResponse", namespace="http://webservices.amazon.com/AWSECommerceService/2011-08-01") //
@XmlAccessorType(XmlAccessType.FIELD)
public class SampleXML {
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public static class OperationRequest {
@XmlTransient
private String RequestId;
@XmlElement(name="RequestId")
public void setRequestId(String id) {
this.RequestId = id;
}
public String getRequestId() {
return RequestId;
}
...
這是應該將JSON字符串返回到瀏覽器的代碼;
@RequestMapping("/samplexml2")
public SampleXML CreateXMLFile2 () throws EncoderException, FileNotFoundException, SAXException {
try {
String requestUrl = null;
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new ResponseErrorHandler());
String decodedUrl = "http://localhost:8080/sample.xml";
String response = restTemplate.getForObject(decodedUrl, String.class);
//Prepare JAXB objects
JAXBContext jaxbContext = JAXBContext.newInstance(SampleXML.class);
Unmarshaller u = jaxbContext.createUnmarshaller();
//Create an XMLReader to use with our filter
XMLReader reader = XMLReaderFactory.createXMLReader();
//Create the filter (to add namespace) and set the xmlReader as its parent.
NamespaceFilter inFilter = new NamespaceFilter("http://webservices.amazon.com/AWSECommerceService/2011-08-01", true);
inFilter.setParent(reader);
//Prepare the input, in this case a java.io.File (output)
InputSource is = new InputSource(new StringReader(response));
//Create a SAXSource specifying the filter
SAXSource source = new SAXSource(inFilter, is);
//Do unmarshalling
SampleXML myJaxbObject = (SampleXML) u.unmarshal(source);
//Convert to myJaxbObject to JSON string here;
return myJaxbObject;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
我想在這一行寫對話; //Convert to myJaxbObject to JSON string here;
我已經閱讀了許多指向該庫的文章。 https://github.com/FasterXML/jackson-module-jaxb-annotations但我無法成功使用它。
我想要一個使用Jackson或MOXy依賴項的示例
您是否嘗試過簡單地將RequestMapping更改為@RequestMapping(value = "/samplexml2", produces = MediaType.APPLICATION_JSON_VALUE)
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.