I have a requirement where some data has to be obtained by connecting to an API.
I have mapped the object returned by query to a hashmap, using the following code–
untypedResult=wt.QueryPermissions();
resp.getWriter().println(" Response for QueryPermissions----");
if(wt.errormsg=="No Error")
{
hMap = (HashMap<String, Integer>) untypedResult;
Set set = hMap.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
resp.getWriter().println(me.getKey() + " : " + me.getValue());
The output as returned by using above code —
Response for QueryPermissions----
get_all_words_popularity : {keyphrase_limit=999, timeout_limit=99, cost_per_call=99, result_limit=999}
Now I tried to map the response (in object) to the following class—
public class wt_queryperm_class {
public Integer keyphrase_limit;
public Integer timeout_limit;
public Integer cost_per_call;
public Integer result_limit;
}
Also, now I modified the code used to display the data as shown below–
//declare new object to store result of QueryPermissions
wt_queryperm_class a;
untypedResult=wt.QueryPermissions();
resp.getWriter().println(" Response for QueryPermissions----");
if(wt.errormsg=="No Error")
{
hMap = (HashMap<String, Integer>) untypedResult;
Set set = hMap.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
a= (wt_queryperm_class)(me.getValue());
resp.getWriter().println(me.getKey() + " : Cost per call=" + a.cost_per_call + "Keyphrase limit=" + a.keyphrase_limit + " Result limit=" + a.result_limit +" Timeout limit=" + a.timeout_limit );
}
However I get the following error when I run the above code–
Problem accessing /keywords_trial_application. Reason:
java.util.HashMap cannot be cast to com.taurusseo.keywords.wt_queryperm_class
Caused by:
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.taurusseo.keywords.wt_queryperm_class
What am I doing wrong here? How do I cast the response correctly so that I can extract each of the 4 values correctly?
The result of the query, given what’s printed and the error you got is a
Map<String, Map<String, Integer>>(or aMap<String, Map<String, String>>if the numbers are stored as Strings).The map has one single key :
"get_all_words_popularity". The associated valud contains 4 keys :"keyphrase_limit","timeout_limit","cost_per_call","result_limit".So your code should rather look like this:
Note that my code
Also understand that a cast doesn’t magically transform an object into another object type. It just allows referencing an object of type A as another type B, and only works if the object is effectively of type B (and thus B has A as ancestor or interface)