on 10-13-2014 3:14 PM
Dear Experts,
I am trying to convert JSON data to XML with the below code which was shared by Hareesh. It works
fine with single item record but when multiple items are there , it doesn't form well formed XML structure.It gives multiple root element.
Code
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONObject;
import com.sap.aii.mapping.api.AbstractTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.api.TransformationInput;
import com.sap.aii.mapping.api.TransformationOutput;
public class xml2json extends AbstractTransformation {
public void transform(TransformationInput in, TransformationOutput out) throws StreamTransformationException {
try {
String sourcexml = ""; String targetxml =""; String line ="";
InputStream ins = in.getInputPayload().getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(ins));
while ((line = br.readLine()) != null)
sourcexml +=line+"\n";
br.close();
JSONObject o = new JSONObject(sourcexml);
targetxml = org.json.XML.toString(o);
out.getOutputPayload().getOutputStream().write(targetxml.getBytes());
}
catch (Exception e) {
throw new StreamTransformationException(e.getMessage());
}
}
}
Payload
{
"items": [
{
"item": {
"Subject": "test wared by wael",
"DocumentID": "55DCE0A476D",
"Sender": "Rebecca",
"SenderDomainName": "user1",
"Date": "2013-02-14 11:14:40",
"DocumentClassID": "11"
}
},
{
"item": {
"Subject": "test wared by wael",
"DocumentID": "55DCE191D5E47",
"Sender": "Dave Froster",
"SenderDomainName": "user11",
"Date": "2013-03-14 11:14:40",
"DocumentClassID": "11"
}
}
]
}
What line of code can be added so that the XML result comes with XML declaration and with 1 root node.
Regards..
Hi Rebecca,
Check this blog. it can be helpful to deal with JSON arrays: Java crumbs » Blog Archive » Converting JSON to XML
Hope this helps.
Regards.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You can even simply append a root tag to the "targetxml"
targetxml = org.json.XML.toString(o);
targetxml = "<root>"+targetxml+"</root>";
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
86 | |
10 | |
10 | |
9 | |
6 | |
6 | |
6 | |
5 | |
4 | |
3 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.