为什么我会收到以下代码段的错误 "java.lang.String cannot be cast to java.util.List"?

Why do I get the error "java.lang.String cannot be cast to java.util.List" with the following snippet?

这是一个示例片段,我在其中尝试从 json 对象获取数组列表,因为我在执行此操作时遇到 class 转换异常。

public static void main(String args[]) throws Exception {
    List<String> arrayList = new ArrayList<String>();
    arrayList.add("a");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("d");
    arrayList.add("e");
    JSONObject json = new JSONObject();
    json.put("raja", "suba");
    json.put("arraylist", arrayList);
    System.out.println("Thus the value of array list is : "+json.get("arraylist"));
    List<String> oldlist = (List<String>) json.get("arraylist");
    System.out.println("Old list contains : "+oldlist);
    System.out.println("The old json contains : "+json.toString());
    String result = json.toString();
    JSONObject json1 = new JSONObject(result);
    System.out.println("The new json value is  : " +json1);
    System.out.println("The value in json for raja is  :" +json1.get("raja"));
    System.out.println("The vlaue of array list is  : "+json1.get("arraylist"));
    List<String> newlist = (List<String>) json1.get("arraylist");
    System.out.println("Thus the value of new list contains : "+newlist);
}

我在获取 oldlist 时没有遇到异常,但在获取 newlist 时遇到了 class 强制转换异常。

  1. 为什么数组列表在第一种情况下被视为对象,而在第二种情况下被视为字符串?
  2. json.toString() 的真正作用是什么?它是将整个 json 对象转换为字符串,例如将双引号 "" 附加到整个 json 对象,还是将其中的每个对象都转换为字符串?

这里的问题是当你

json.put("arraylist", arrayList);

您明确要求列表序列化。这意味着将执行底层逻辑,以便将与 class 相关的元数据保存到 JSON 对象中。但是,当您执行 json.toString() 时,此元数据会丢失,您最终会得到一个旧的纯字符串对象。然后,当您尝试在运行时反序列化此 String 时,您会得到一个 ClassCastException,因为它实际上不知道如何将该 String 转换为列表。

要回答您的第二个问题,JSONObject.toString() returns JSON 格式的对象的字符串表示形式。这意味着如果您有一个 ArrayList,而不是具有具有 ArrayList.toString() 值的字段,您将具有一个具有列表值的数组元素。