我正在尝试将我的Xml字符串转换为json对象。我正在使用org.Json包。我已经从wolfram alpha服务器请求了信息。服务器返回xml,我想使用org.json包将其转换为json。我试图使用的方法是静态的,它位于XML类中。我创建了一个JSONObject方法,认为我会转换,但我不断收到错误消息。
这是我的主要方法的代码。
import java.net.*;
import java.io.*;
import org.json.*;
import java.net.URLConnection;
import java.util.Scanner;
import java.net.URL;
import javax.swing.*;
public class Test {
public static void main(String[] args)throws IOException, JSONException{//Beginning of class
// TODO Auto-generated method stub
String appID = "YWT4UP-Y9W7AREAHJ";
String search = "bird";
URL wolframData = new URL("http://api.wolframalpha.com/v2/query?input="+search+"&appid="+appID);
URLConnection connection = wolframData.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//reads in the data
String xmlDoc;
while((xmlDoc = in.readLine()) != null) //converts buffer reader to string
System.out.println(xmlDoc);
in.close();
JSONObject jsonDoc = (JSONObject) XML.toJSONObject(xmlDoc);
}//End of method
}//End of class
以下是到达将xml转换为json的代码时显示的错误消息:
Exception in thread "main" java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:85)
at org.json.XMLTokener.<init>(XMLTokener.java:55)
at org.json.XML.toJSONObject(XML.java:329)
at Test.main(Test.java:31)
答案 0 :(得分:1)
我认为答案应该是,
import java.net.*;
import java.io.*;
import org.json.*;
import java.net.URLConnection;
import java.util.Scanner;
import java.net.URL;
import javax.swing.*;
public class Test {
public static void main(String[] args)throws IOException, JSONException{//Beginning of class
// TODO Auto-generated method stub
String appID = "YWT4UP-Y9W7AREAHJ";
String search = "bird";
URL wolframData = new URL("http://api.wolframalpha.com/v2/query?input="+search+"&appid="+appID);
URLConnection connection = wolframData.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//reads in the data
String xmlDoc;
StringBuilder sb = new StringBuilder();
while((xmlDoc = in.readLine()) != null) { //converts buffer reader to string
System.out.println(xmlDoc);
sb.append(xmlDoc);
}
in.close();
JSONObject jsonDoc = (JSONObject) XML.toJSONObject(sb.toString());
}//End of method
}//End of class