1

我正在尝试将我的 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)
4

1 回答 1

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
于 2016-04-08T20:25:16.577 回答