Site icon NgDeveloper

[Resolved] java.util.LinkedHashMap cannot be cast to org.json.simple.JSONObject

[Resolved] java.util.LinkedHashMap cannot be cast to org.json.simple.JSONObject

This issue may happen for various use cases, I have explained my use case below, hope it helps someone.

My JSON string / JSON response sample is:

{"itemName":"Amazon","id":1}

 

code generates java.util.LinkedHashMap cannot be cast to org.json.simple.JSONObject exception:

for(int i=0;i<selectedStoresJsonArray.size();i++){
 JSONObject jsonObj = (JSONObject) selectedStoresJsonArray.get(i);
 if(null!=jsonObj.get("itemName") && !jsonObj.get("itemName").toString().isEmpty()){
  tempSelectedStores.add(jsonObj.get("itemName").toString());
 }
}

 

Here JSONObject is not knowing the type of the response received while deserializing, so it is throwing this exception. Because by default json deserialize picks linkedhashmap for the non-identifiable objects during deserialize process.

 

Code Fixed:

for(int i=0;i<selectedStoresJsonArray.size();i++){
 HashMap<String, String> passedValues = (HashMap<String, String>) selectedStoresJsonArray.get(i);
 for (Entry<String, String> mapTemp : passedValues.entrySet()) {
  if (mapTemp.getKey().equalsIgnoreCase("itemName")) {
   tempSelectedStores.add(mapTemp.getValue());
  }
 }
}

Here I am iterating using hashmap to store the values of the json object as key and value objects. With the help of the same I am getting and adding only the itemNames in my arraylist.

 

To fix and avoid this error java.util.LinkedHashMap cannot be cast to org.json.simple.JSONObject always plan to use Hashmap for deserialization instead of using JSON Object/Object or your custom objects.

Hope this helps!

Exit mobile version