Abhishek Mishra :
I am working with an api and using Gson to convert Json response into java object. The code is working fine and I am getting the required results, but when I am writing test cases I am getting a ClassCastException
.
GET Call:
String jsonResponse = getData(parameter1,parameter2);//api call
if(!StringUtils.equalsIgnoreCase(jsonResponse, "null"))
{`JSONObject jsonObject = new JSONObject(jsonResponse);`
Gson gson = new Gson();
somejavaObject = gson.fromJson((String) jsonObject.get("data"),
javaObject.class);
}
POST call:
ObjectMapper mapper = new ObjectMapper();
String objectString = mapper.writeValueAsString(object);
JSONObject request = new JSONObject();
request.put("data", objectString);
request.put("otherData", someValue);
//then POST call
Test case for GET call:
String json = "{\"data\": {\"value1\": {\"v1\": 123, \"v2\": 456}, \"list\": [{\"l1\": 123, \"l2\" :456}]}}";
PowerMockito.doReturn(json).when(spy,"getData",parameters);
The above code is working for the api but failing the test case at the above line and throwing me error:
java.lang.ClassCastException: org.json.JSONObject cannot be cast to java.lang.String
Abhishek :
I found the solution. The problem was that I casted to a wrong type.
somejavaObject = gson.fromJson((String) jsonObject.get("data"), javaObject.class);
I changed the line above to
somejavaObject = gson.fromJson( jsonObject.get("data").toString(), javaObject.class);
and it works now.