Parsing external XML to JSON in Java?

ⅰ亾dé卋堺 提交于 2019-12-20 01:52:11

问题


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.

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.


回答1:


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

  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);
    



回答2:


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

  • http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true

The above link is taken directly from:

  • http://code.google.com/apis/maps/documentation/geocoding/#JSON


来源:https://stackoverflow.com/questions/3812091/parsing-external-xml-to-json-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!