Renaming an inner element cant be done as like renaming root element, while converting an xml to json using java
I have the following code with me:
import org.json.JSONObject; import org.json.XML; public class Xml2Json { public static void main(String[] args) { String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>"; JSONObject jsonObject = XML.toJSONObject(xmlString); jsonObject.put("employees", jsonObject.remove("users")); System.out.println(jsonObject); }}
It produces the output like below:
{"employees":{"report":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}}.
But when i tried to rename ‘report’ to ‘manual’ in the same way,
jsonObject.put("Manual", jsonObject.remove("report"));
It didnt produced any chane in the ouput.
the output i needed is:
{"employees":{"Manual":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}}
Try this:
jsonObject.put("Manual", jsonObject.getJSONObject("users").remove("report"));
report
is nested in users
or employees
. So first you have to get its root object.
Update
If you want to have a json as below
{"employees":{"Manual":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}}
then your code should be like this:
jsonObject.getJSONObject("users") .put("Manual", jsonObject.getJSONObject("users").remove("report")); jsonObject.put("employees", jsonObject.remove("users"));