使用Jackson或Moxy依赖项将Java Jaxb对象转换为JSON



我正在处理将从XML源返回JSON响应的API。我已经使用RestTemplateJAXB从源获取XML字符串,然后使用StringReaderUnmarshaller来创建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-notations,但我无法成功使用它。

我想要一个使用Jackson或Moxy依赖项的示例

您是否尝试过将请求映射更改为 @RequestMapping(value = "/samplexml2", produces = MediaType.APPLICATION_JSON_VALUE)

最新更新