在Java中将外部XML解析为JSON? [英] Parsing external XML to JSON in Java?

查看:128
本文介绍了在Java中将外部XML解析为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我将如何执行此操作? (不,这不是功课)
请注意,最好在标准库中完成。目前我正试图解决是否可以使用例如SAX。

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.

推荐答案

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

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


  1. 连接到URL并下载XML作为字符串:

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


  • 这里。 (您必须编译它并确保类在您的类路径上。)

  • Download the JSON library from here. (You will have to compile it and ensure that the classes are on your classpath.)

    将XML转换为JSON对象:

    Convert the XML into a JSON Object:

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


  • 这篇关于在Java中将外部XML解析为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆