Issue
I have the below function
public String convertToXml(String json) throws JSONException {
JSONObject jsonObject = new JSONObject(json);
String xml = XML.toString(jsonObject);
return xml;
}
that is converting JSON String to XML. However, some attributes are being swapped from their position for example
{"isbn": "123-456-222",
"author":
{
"lastname": "Doe",
"firstname": "Jane"
},
"editor":
{
"lastname": "Smith",
"firstname": "Jane"
},
"title": "The Ultimate Database Study Guide",
"category": ["Non-Fiction", "Technology"]
}
becomes
<editor>
<firstname>Jane</firstname>
<lastname>Smith</lastname>
</editor>
<author>
<firstname>Jane</firstname>
<lastname>Doe</lastname>
</author>
<isbn>123-456-222</isbn>
<title>The Ultimate Database Study Guide</title>
<category>Non-Fiction</category>
<category>Technology</category>
How can I make sure that the XML has the same order as JSON? I used org.json.XML from
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
Solution
I downloaded the Official JSON-java repository and changed \src\main\java\org\json\JSONObject.java
constructor from
public JSONObject() {
this.map = new HashMap();
}
to
public JSONObject() {
this.map = new LinkedHashMap();
}
then i compiled it again to .jar file and include it to my project.
Answered By - lewis machilika