Java JSONSimple Parser

时间:2014-06-23 08:21:11

标签: java json

我尝试使用JSONArray将数据从php脚本解析到我的Java应用程序。 这是php输出:

{"name":"test"}

这是我从JSONSimple文档中获得的Java代码:

try {
    String urlParameters = "test";    
    URL url = new URL("http://localhost:8080/Test");
    URLConnection conn = url.openConnection();

    conn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(urlParameters);
    writer.flush();

    String line;

    BufferedReader reader = new BufferedReader(new  InputStreamReader(conn.getInputStream()));

    while ((line = reader.readLine()) != null) {
        System.out.println(line);

        Object obj=JSONValue.parse(line);
        JSONArray array=(JSONArray)obj;

        System.out.println(array.get(0));     
    }

    writer.close();
    reader.close();

} catch (IOException e) {
    System.out.print("ERROR: 1");
    return;
}

它没有在编辑器中显示任何错误但是当我尝试运行该程序时,我收到以下错误消息:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

有人知道解决这个问题吗?任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

JSON对象:

{ "key1": "value", "key2" : "value2", ....}

JSON数组:[ object1, object2,...]

您正在尝试将对象转换为数组,这就是问题:

Object obj=JSONValue.parse(line);
JSONArray array=(JSONArray)obj; //INCORRECT

将其转换为JSONObject而不是

答案 1 :(得分:0)

JSONParser jsonParser = new JSONParser(); 
JSONObject jsonObject = (JSONObject) jsonParser.parse(your php string);
// get a String from the JSON object  
String firstName = (String) jsonObject.get("name");  

答案 2 :(得分:0)

你的php输出{“name”:“test”}是一个JSONObject,而不是JSONArray ..

您不能将JSON对象强制转换为JSONarray

相关问题