0

我正在使用 Axis2 1.6.4 来实现 REST Json WebServices ( https://axis.apache.org/axis2/java/core/docs/json_support.html ),当 Jettison 将 Json 对象转换为 XML 时,我会遇到问题。没有“根”元素。细节:

如果请求是:

{"name":"John","age":30}

那么服务器端的 XML OMElement 是:

<name>John</name

所以错过了年龄元素

相反,如果请求是:

{person:{"name":"John","age":30}}

那么服务器端的 XML OMElement 是:

<person><name>John</name><age>30</age></person>

谢谢你的帮助,马蒂

4

1 回答 1

0

我找到了解决这个 JSON-> XML 转换问题的方法。感谢这篇文章:如何使用 Axis2 JSON,我意识到我能够在将输入 json 转换为 XML 之前访问它,并且还可以从 json 字符串创建一个 OMElement。所以当输入是一个json请求时,我用一个json“根”元素包装它,然后将它转换为XML而不丢失数据。如果它对某人有用,下面是获取输入 json 字符串的源代码和将 json 字符串转换为 OMElement 的源代码

获取输入 json 字符串并包装成根

    OMSourcedElement source=(OMSourcedElement )msg;
    AbstractJSONDataSource jsonSoucre=(AbstractJSONDataSource)source.getDataSource();

    MessageContext msgCtxt= MessageContext.getCurrentMessageContext();

    JSONDataSource jsonRequestEnvDS= new JSONDataSource(new StringReader("{\"JSONEnvelope\": " + jsonSoucre.getObject() + " }"), msgCtxt);
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMSourcedElement omRequest =  factory.createOMElement(jsonRequestEnvDS,null,null);

从 json 字符串创建 OMElement

    String jsonString="{...}";
    JSONDataSource jsonDS= new JSONDataSource(new StringReader(jsonString),msgCtxt);
    factory = OMAbstractFactory.getOMFactory();
    OMSourcedElement resonseJson =  factory.createOMElement(jsonDS,null,null);

    return  resonseJson;
于 2018-07-23T07:09:32.197 回答