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

时间:2022-12-01 11:14:18

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。

2 个解决方案

#1


5  

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:

    连接到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. Download the JSON library from here. (You will have to compile it and ensure that the classes are on your classpath.)

    从这里下载JSON库。 (您必须编译它并确保类在您的类路径上。)

  3. Convert the XML into a JSON Object:

    将XML转换为JSON对象:

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

#2


3  

Why don't you retrieve the Google geocode as JSON in the first place?

为什么不首先将Google地理编码检索为JSON?

The above link is taken directly from:

以上链接直接来自:

#1


5  

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:

    连接到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. Download the JSON library from here. (You will have to compile it and ensure that the classes are on your classpath.)

    从这里下载JSON库。 (您必须编译它并确保类在您的类路径上。)

  3. Convert the XML into a JSON Object:

    将XML转换为JSON对象:

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

#2


3  

Why don't you retrieve the Google geocode as JSON in the first place?

为什么不首先将Google地理编码检索为JSON?

The above link is taken directly from:

以上链接直接来自: