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
.
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.