【问题标题】:Axis2 JSon Support (Jettison) bad xml conversionAxis2 JSON 支持 (Jettison) 错误的 xml 转换
【发布时间】:2018-02-02 16:56:13
【问题描述】:

我正在使用 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>

感谢您的帮助, 马蒂

【问题讨论】:

    标签: json axis2 jettison


    【解决方案1】:

    我找到了解决这个 JSON->XML 转换问题的方法。感谢这篇文章:How to use 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2011-06-05
      • 2019-10-20
      • 2011-01-07
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多