Reputation: 103
I have this json string:-
{
"mkt": {
"-st": "NSW",
"-pc": "2150",
"-lo": "PARRAMATTA",
"-pt": "U",
"-notify_by": "email",
"-notify_when": "any",
"stat": [
{
"-code": "DSR_PLUS",
"-change": "falls below",
"-val": "50"
},
{
"-code": "TV",
"-change": "rises above",
"-val": "450000"
}
]
}
}
I want to convert this as XML like this:-
<?xml version="1.0" encoding="UTF-8" ?>
<mkt st="NSW" pc="2150" lo="PARRAMATTA" pt="U" notify_by="email" notify_when="any">
<stat code="DSR_PLUS" change="falls below" val="50" />
<stat code="TV" change="rises above" val="450000" />
</mkt>
I am using this code to convert JSON string to XML:-
JSONObject o = new JSONObject(JSONSTring);
String xml = org.json.XML.toString(o);
But this is giving me wrong XMl( XML without properties)
Upvotes: 1
Views: 5632
Reputation: 422
If you want to use org.json classes like JSONObject and XML, then be aware that there is no natural mapping between JSON and XML. Instead of using the the XML class, try the JSONML class from the same library, that is what it is for. Note how you have to modify the JSON text to be parsable by JSONML. You can find the BNF for JSONML on this page: http://jsonml.org
String jsonXmlStr =
"{"+
"\"st\": \"NSW\","+
"\"notify_by\": \"email\","+
"\"notify_when\": \"any\","+
"\"pc\": 2150,"+
"\"lo\": \"PARRAMATTA\","+
"\"pt\": \"U\","+
"\"childNodes\": ["+
"{"+
"\"val\": 50,"+
"\"code\": \"DSR_PLUS\","+
"\"change\": \"falls below\","+
"\"tagName\": \"stat\""+
"},"+
"{"+
"\"val\": 450000,"+
"\"code\": \"TV\","+
"\"change\": \"rises above\","+
"\"tagName\": \"stat\""+
"}"+
"],"+
"\"tagName\": \"mkt\""+
"}";
JSONObject jsonXmlObject = new JSONObject(jsonXmlStr);
System.out.println(JSONML.toString(jsonXmlObject));
The above JSON text and code fragment will produce the XML you want:
<mkt st="NSW" notify_by="email" notify_when="any" pc="2150" lo="PARRAMATTA" pt="U">
<stat val="50" code="DSR_PLUS" change="falls below"/>
<stat val="450000" code="TV" change="rises above"/>
</mkt>
Upvotes: 1
Reputation: 167
You could use (changing the attributes tag for "@" instead of "-". (this is a groovy script, but it's almost the same as in Java)
import net.sf.json.JSON
import net.sf.json.JSONSerializer
import net.sf.json.xml.XMLSerializer
JSON json = JSONSerializer.toJSON( jsonString )
XMLSerializer xmlSerializer = new XMLSerializer()
xmlSerializer.setTypeHintsCompatibility( false )
def xml = xmlSerializer.write( json )
Watch out! you might have problems with your json If it has complicate arrays, in fact.. that's what I'm looking for a way to convert json to xml with properties.
<mkt lo="PARRAMATTA" notify_by="email" notify_when="any" pc="2150" pt="U" st="NSW">
<stat>
<e change="falls below" code="DSR_PLUS" val="50"/>
<e change="rises above" code="TV" val="450000"/>
</stat>
</mkt>
If this works for you perfect otherwise.. we'll have to wait for someone to give us another solution.
Upvotes: 1