XML到JSON使用JSON-LIB [英] XML to Json using Json-lib
本文介绍了XML到JSON使用JSON-LIB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图做Android的一个项目,我已经从web文档的XML,我想以JSON转换。
I'm trying to do a project in Android where I have a document xml from a web and i want to convert in Json.
我想这样的:
URL url;
InputStream in;
try {
url = new URL("http://www.aemet.es/xml/municipios/localidad_41091.xml");
in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String result, line = reader.readLine();
result = line;
while((line=reader.readLine())!=null){
result+=line;
}
XMLSerializer serializer = new XMLSerializer();
JSON json = serializer.read( result );
System.out.println(json.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
但不工作...有人可以帮助我
but does not work ... can someone help me
推荐答案
将整个XML文档作为字符串而不是读一行行
Send the entire xml document as string instead of reading line by line
import java.io.InputStream;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
public class ConvertXMLtoJSON {
public static void main(String[] args) throws Exception {
InputStream is =
ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml");
String xml = IOUtils.toString(is);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read( xml );
System.out.println( json.toString(2) );
}
}
这篇关于XML到JSON使用JSON-LIB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文