Parsing external XML for JSON in Java?

So, am I sitting here with a Google Geocoder that returns XML via 'GOOGLE_URL / xml? address = input & sensor = false '. I need to get it using Java and parse it into a JSON object and send it forward.

How am I going to do this? (No, this is not homework) Please note that it is advisable to do this in standard libraries. At the moment I am trying to work if it can be done, for example, SAX.

+3
source share
2 answers

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

  • Connect to the URL and load 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();
    
  • JSON . ( , .)

  • XML JSON:

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

Source: https://habr.com/ru/post/1766943/


All Articles