使用Jackson或MOXy依赖项将Java JAXB对象转换为JSON

时间:2017-09-19 09:57:51

标签: java json xml jaxb

我正在开发一个API,它将从XML源返回JSON响应。我使用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-annotations但我无法成功使用它。

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

1 个答案:

答案 0 :(得分:0)

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