I was working on a project a while back and one of the requirement was to convert xml to json for one feed which was in xml format. We were using mongodb to store the feed so I was looking for a simple solution. I came across many libraries and finally used json.org
. Find here how to convert XML to JSON in Java.
The only problem was with Array, I wanted the array to be in the same order as it was in the XML file. So I had to make a small modification to the JSONObject
class. You need to replace the HashMap
with the LinkedHashMap
in the JSONObject
class file. It should be present in two places, inside the JSONObject()
& JSONObject(Map
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public JSONObject() { this.map = new LinkedHashMap<String, Object>(); } public JSONObject(Map<String, Object> map) { this.map = new LinkedHashMap<String, Object>(); if (map != null) { Iterator<Entry<String, Object>> i = map.entrySet().iterator(); while (i.hasNext()) { Entry<String, Object> entry = i.next(); Object value = entry.getValue(); if (value != null) { this.map.put(entry.getKey(), wrap(value)); } } } } |
The implementation is simple. Here is the code:
1 2 |
String xml = FileUtils.readFileToString(new File("test.xml")); System.out.println(org.json.XML.toJSONObject(xml).toString()); |
Piyush says
If you have a valid dtd file for the xml snippet, then you can easily convert xml to json and json to xml using the open source eclipse link jar. Detailed sample JAVA project can be found here: http://cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html
Kishore says
Hi,
So you updated the JSONObject java source, to include your method?
A Developer Diary says
Yes, the method would be there, just change the HashMap to LinkedHashMap
naveen says
From where FileUtils class is imported.
Mauro says
how do I change jsonobject?