我想将我的xml文件转换为json ...但是下面的代码显示空指针异常..我不知道出了什么问题。
public class Xmljson {
private URL url = null;
private InputStream inputStream = null;
public void getXMLfromJson() {
try{
url = Xmljson.class.getClassLoader().getResource("datafile.xml");
inputStream = url.openStream();
String xml = IOUtils.toString(inputStream);
JSON objJson = new XMLSerializer().read(xml);
System.out.println("JSON data : " + objJson);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if (inputStream != null) {
inputStream.close();
}
url = null;
} catch (IOException ex) {}
}
}
public static void main(String[] args) {
new Xmljson().getXMLfromJson();
}
}
在这里显示例外
url = Xmlto.class.getClassLoader().getResource("data");
inputStream = url.openStream();
NPE IS
java.lang.NullPointerException
at pkg.news.Xmlto.getXMLfromJson(Xmlto.java:19)
at pkg.news.Xmlto.main(Xmlto.java:35)
来自
http://tutorial4java.blogspot.in/2013/04/xml-to-json-conversion.html
答案 0 :(得分:2)
检查一下......这很有效......
public class Xml2json {
static String line="",str="";
public static void main(String[] args) throws JSONException, IOException {
String link = "data.xml";
BufferedReader br = new BufferedReader(new FileReader(link));
while ((line = br.readLine()) != null)
{
str+=line;
}
JSONObject jsondata = XML.toJSONObject(str);
System.out.println(jsondata);
}
}
答案 1 :(得分:0)
应该有效
url = XMLjson.class.getClassLoader().getResource("datafile.xml");
您是否也添加了这些陈述,
import java.io.InputStream;
import java.net.URL;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
看看这里 http://tutorial4java.blogspot.in/2013/04/xml-to-json-conversion.html