简体   繁体   中英

XML to JSON Conversion Proper Format

I know that the type of question i am going to ask is asked many times but there still i fell my question is different because i am not able to find the right answer,

I need to covert XML string to JSON format

My XML Format Looks Like

<employee>
<empId>1</empId>
<address>India</address>
</employee>

I don't have employee class with me and this root tag can be anything next time so i am using xml parsing to form a XML and then i am covering the xml string to JSON

JSONObject xmlJSONObj = XML.toJSONObject(data);
String jsonPreetyPrintString = xmlJSONObj.toString(1);
response = jsonPreetyString;

and my JSON output comming like this

{"employee":{
"empId":1,
"address":"India"
}
}

But, I am expecting my output to looks like

{
 "empId":1,
 "address":"India"
}

Please suggest me which way i can achive this .

If the name of the root element is known, eg the name of the class, you can simply use JSONObject#getJSONObject:

http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html#getJSONObject(java.lang.String)

@Test
public void testJSON() throws JSONException {
    JSONObject jsonObj = new JSONObject().put("A", new JSONObject().put("a", 1).put("b", 5));

    String[] fieldNames = JSONObject.getNames(jsonObj);
    String key = fieldNames[0];

    System.out.println(jsonObj); // {"A":{"a":1,"b":5}}
    System.out.println(jsonObj.getJSONObject(key)); // {"a":1,"b":5}
}

private class A {
    private int a = 1; 
    private int b = 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM