引入jar包
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
实现代码
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING = String.format("http://127.0.0.1:9920/eureka/apps");
public static void main(String[] args) {
try {
URL url = new URL(TEST_XML_STRING);
URLConnection open = url.openConnection();
InputStream input = open.getInputStream();
String result = org.apache.commons.io.IOUtils.toString(input,"utf-8");
JSONObject xmlJSONObj = XML.toJSONObject(result);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
} catch (Exception je) {
System.out.println(je.toString());
}
}