有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

json Java JSONSimple解析器

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

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

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


共 (3) 个答案

  1. # 1 楼答案

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

    不能将JSONobject类型转换为JSONarray

  2. # 2 楼答案

    JSON对象:

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

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

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

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

    把它换成JSONObject

  3. # 3 楼答案

    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");