Wednesday, May 11, 2016

How to deal with spaces when doing conversions from json to xml or wise versa in WSO2 ESB

In this blog post what I'm going to mention is a valuable feature which resides in WSO2 ESB.

When we think of json, we can have spaces in json element names, for example, below is a valid json string
{
  "abc def" : "this is a sample value"
}
but when we think about XML specification [1], [2], XML element names cannot have spaces, In WSO2 ESB we can convert json to xml and vise versa, so how are we going to convert above mentioned json(with space for json element name) and have a valid XML string,

What we have to do is simple, we have to specify "synapse.commons.json.buildValidNCNames" to value "true" in "$ESB_HOME/repository/conf/synapse.properties" file, then ESB will do the conversion as follows
input Json -
 
{
  "abc def" : "this is a sample value"
}
output XML -
 
this is a sample value

And this works other way around as well, say you need to convert XML to json and json element should need to have a space within it, then you can use "_JsonReader_32_" in xml to get the space in json output, for example,
input xml -
 
this is a sample value
output json -
  
{
  "abc def" : "this is a sample value"
}

For your reference below is a sample API configuration which will convert json input and send you back converted xml



    
        
            
            
            
        
        
        
        
    

you can invoke above API using a Rest client with POST url "http://localhost:8280/sample3/abc" and a json payload. Hope this helps

[1] - https://www.w3.org/TR/REC-xml/#sec-common-syn
[2] - http://www.w3schools.com/xml/xml_elements.asp

No comments :