bd96500e110b49cbb3cd949968f18be7.png

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:

John

So age element is missed

Instead, if request is:

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

Then XML OMElement at server side is:

John30

Thanks for your help,

Martí

解决方案

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;

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐