我要求通过连接到API来获取某些数据。
我已使用以下代码将查询返回的对象映射到散列映射 -
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());
使用上面的代码返回的输出 -
Response for QueryPermissions----
get_all_words_popularity : {keyphrase_limit=999, timeout_limit=99, cost_per_call=99, result_limit=999}
现在我尝试将响应(在对象中)映射到以下类---
public class wt_queryperm_class {
public Integer keyphrase_limit;
public Integer timeout_limit;
public Integer cost_per_call;
public Integer result_limit;
}
此外,现在我修改了用于显示数据的代码,如下所示 -
//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 );
}
但是,当我运行上面的代码时,我收到以下错误 -
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
我在这里做错了什么?如何正确转换响应,以便我可以正确提取每个值?
答案 0 :(得分:1)
查询的结果,给定打印的内容并且您得到的错误是Map<String, Map<String, Integer>>
(如果数字存储为字符串,则为Map<String, Map<String, String>>
。
地图只有一个密钥:"get_all_words_popularity"
。关联的valud包含4个键:"keyphrase_limit"
,"timeout_limit"
,"cost_per_call"
,"result_limit"
。
所以你的代码应该是这样的:
untypedResult = wt.queryPermissions();
resp.getWriter().println(" Response for QueryPermissions----");
if("No Error".equals(wt.errormsg)) {
Map<String, Map<String, Integer> hMap =
(Map<String, Map<String, Integer>) untypedResult;
for (Map.Entry<String, Map<String, Integer>> me : hMap.entrySet()) {
Map<String, Integer> value = me.getValue();
WtQueryPerm perm = new WtQueryPerm(value.get("keyphrase_limit"),
value.get("timeout_limit"),
value.get("cost_per_call"),
value.get("result_limit"));
resp.getWriter().println(me.getKey()
+ " : Cost per call=" + perm.getCostPerCall()
+ ", Keyphrase limit=" + perm.getKeyphraseLimit()
+ ", Result limit=" + perm.getResultLimit()
+ ", Timeout limit=" + perm.getTimeoutLimit());
}
}
请注意我的代码
还要理解,强制转换不会将对象神奇地转换为另一种对象类型。它只允许引用类型A的对象作为另一种类型B,并且只有当对象实际上是B类时才有效(因此B将A作为祖先或接口)
答案 1 :(得分:0)
看起来你想从HashMap填充Bean。雅加达的Beanutils为此提供了帮助。
wt_queryperm_class bean=new wt_queryperm_class();
BeanUtils.populate(bean, hmap);