在 Java 中将外部 XML 解析为 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3812091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:28:52  来源:igfitidea点击:

Parsing external XML to JSON in Java?

javaxmljsonsax

提问by Mantar

So I'm sitting here with Google Geocoder, which returns an XML via 'GOOGLE_URL/xml?address=input&sensor=false'. I need to fetch it by using Java and parse it into a JSON object and send it onwards.

所以我坐在这里使用 Google Geocoder,它通过“GOOGLE_URL/xml?address=input&sensor=false”返回一个 XML。我需要使用 Java 获取它并将其解析为 JSON 对象并继续发送。

How would I go about to do this? (No this is not homework) Note that it should preferably be done within the standard libraries. At the moment I'm trying to work out if it can be done with for example SAX.

我该怎么做呢?(不,这不是作业)请注意,最好在标准库中完成。目前我正在尝试解决它是否可以用例如 SAX 来完成。

回答by dogbane

Here is a working example which shows how to connect to a URL, download XML and convert it to JSON format:

这是一个工作示例,显示了如何连接到 URL、下载 XML 并将其转换为 JSON 格式:

  1. Connect to a URL and download the XML as a string:

    String str = "http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
    URL url = new URL(str);
    InputStream is = url.openStream();
    int ptr = 0;
    StringBuilder builder = new StringBuilder();
    while ((ptr = is.read()) != -1) {
        builder.append((char) ptr);
    }
    String xml = builder.toString();
    
  2. Download the JSON library from here. (You will have to compile it and ensure that the classes are on your classpath.)

  3. Convert the XML into a JSON Object:

    JSONObject jsonObject = XML.toJSONObject(xml);
    System.out.println(jsonObject);
    
  1. 连接到 URL 并将 XML 作为字符串下载:

    String str = "http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
    URL url = new URL(str);
    InputStream is = url.openStream();
    int ptr = 0;
    StringBuilder builder = new StringBuilder();
    while ((ptr = is.read()) != -1) {
        builder.append((char) ptr);
    }
    String xml = builder.toString();
    
  2. 这里下载 JSON 库。(您必须编译它并确保这些类在您的类路径上。)

  3. 将 XML 转换为 JSON 对象:

    JSONObject jsonObject = XML.toJSONObject(xml);
    System.out.println(jsonObject);