javajsonsimple解析器

javajsonsimple解析器,java,json,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.set

我正试图用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;
}
在de编辑器中不会显示任何错误,但当我尝试运行该程序时,会收到以下错误消息:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
有人知道解决这个问题的方法吗?任何帮助都将不胜感激。

JSON对象:

{ "key1": "value", "key2" : "value2", ....}
JSON数组:
[object1,object2,…]

您试图将对象强制转换为数组,这就是问题所在:

Object obj=JSONValue.parse(line);
JSONArray array=(JSONArray)obj; //INCORRECT
将其强制转换为一个
JSONObject

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

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");  
不能将JSONobject类型转换为JSONarray