Search This Blog

Thursday 26 September 2013

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject


Sep 27, 2013 11:42:56 AM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerExceptionSEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP containerjava.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject

 The Exception is very clear ..
org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject
since ,  we are using making use of two diff libs here ..

 The problem here is that the "jsonParser.parse("-string-");" will return a org.json.simple.JSONObject (json-simple-1.1.1.jar) && we are trying to store in into a JsonObject vreated via net.sf.json.JSONObject (json-lib-2.2.jar)

 Solution -simply remove the use of "net.sf.json.JSONObject" to create a JsonObject & INSTEAD use org.json.simple.JSONObject create a JsonObject.


 Hence, your code will also be slightly modified given the way you extract key-values going further..

 BEFORE-- 

  //## here the requisite jar(json-simple-1.1.1.jar) for JsonParser is included in the jersey bundle itself..
org.json.simple.parser.JSONParser jsonParser = new JSONParser();

// ## Included json-lib-2.2.jar for using JsonObject ,etc..
net.sf.json.JSONObject jsonObj;
try {
jsonObj = (JSONObject) jsonParser.parse(requestParam);
name = jsonObj.getString("name");
phone = jsonObj.getString("phone");
email = jsonObj.getString("email");

} catch (ParseException e) {
e.printStackTrace();
}

AFTER --

//## here the requisite jar(json-simple-x.x.jar) for JsonParser is included in the jersey bundle itself..
org.json.simple.parser.JSONParser jsonParser = new JSONParser();

// ## Included json-lib-2.2.jar for using JsonObject ,etc..
org.json.simple.JSONObject jsonObj = new JSONObject();
try {
jsonObj = (JSONObject) jsonParser.parse(requestParam);
name = jsonObj.get("name").toString();
phone = jsonObj.get("phone").toString();
email = jsonObj.get("email").toString();

/*phone = jsonObj.getString("phone");
email = jsonObj.getString("email");*/

} catch (ParseException e) {
e.printStackTrace();
}

1 comment:

  1. i am getting the same error even i perform the same operation.

    ReplyDelete