Search code examples
javajsonstringarraylistclasscastexception

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


Here is a sample snippet where I am trying to get array list from a json object by I am getting class cast exception while doing this.

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

I am not getting exception while obtaining oldlist but I'm getting class cast exception while obtaining newlist.

  1. Why the array list is treated as an object in the first case but as a string in the second case?
  2. What json.toString() really does? Does it converts the entire json object to string like appending double quotes "" to entire json object or does it converts each and every object within it into string?

Solution

  • The problem here is that when you do

    json.put("arraylist", arrayList);
    

    you are explicitly asking for a list serialization. This means that underlying logic will be performed in order to save class-related metadata into the JSONObject. When you do json.toString(), though, this metadata are lost and you end up with a old plain String object. Then, when you try to deserialize this String at runtime, you get a ClassCastException because it doesn't really know how to convert that String into a list.

    To answer your second question, JSONObject.toString() returns a String representation of an object in JSON format. This means that if you have an ArrayList, instead of having a field with the ArrayList.toString() value, you will have an array element with the list values.