Axis2 JSon Support (Jettison) bad xml conversion

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í

Upvotes: 0

Views: 428

Answers (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;

Upvotes: 0

Related Questions