Axis2 JSon Support (Jettison) bad xml conversion

南笙酒味 提交于 2019-12-25 02:46:35

问题


I am using Axis2 1.6.4 to implement REST Json WebServices (https://axis.apache.org/axis2/java/core/docs/json_support.html) and I face an issue when Jettison converts Json object To XML if it does not have a "root" element. Details:

If request is:

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

Then XML OMElement at server side is:

<name>John</name

So age element is missed

Instead, if request is:

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

Then XML OMElement at server side is:

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

Thanks for your help, Martí


回答1:


I've founda work around to overcome this JSON->XML conversion issue. Thanks to this post:How to use Axis2 JSON, I've realized I am able to access input json before converting it to XML, and also to create an OMElement from a json string. So when input is a json request, I wrap it with a json "root" element, and then convert it to XML without losing data. If it could be useful to someone, below is the source code to get input json string and the source code to convert json string to OMElement

Get input json string and wrap into a root

    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);

Create an OMElement from a json string

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

    return  resonseJson;


来源:https://stackoverflow.com/questions/48587430/axis2-json-support-jettison-bad-xml-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!