gson.fromJson为动态键返回null [英] gson.fromJson returns null for dynamic keys
问题描述
{
richerich我在Android应用程序中使用gson解析以下响应: :{
id:19250176,
name:RichERich,
profileIconId:744,
summonerLevel:30,
revisionDate :1425977347000
alma:{
id:19250174,
name:Alma,
profileIconId :764,
summonerLevel:30,
revisionDate:14259773423424
}
}
关键richeric是一个动态的关键字,可能会改变,我的响应字符串中还可能有其他响应对象,例如richeric。
我为此创建了类:
public class SummonerDto {
private long id;
私人字符串名称;
private int profileIconId;
私人长期修订日期;
私人长summonerLevel;
// getters,setters ...
}
和我的响应类:
公共类SummonerInfoResponse {
私人地图< String,SummonerDto>召唤师;
公共地图< String,SummonerDto> getSummoners(){
返回summoners;
}
public void setSummoners(Map< String,SummonerDto> summoners){
this.summoners = summoners;
}
}
我使用下面的一段代码:
return gson.fromJson(response,SummonerInfoResponse.class);
但它返回null。任何人都可以告诉我为什么?
谢谢。
解决方案。
我用HashMap扩展了我的响应类,现在我可以将响应作为一个gson对象。这里是完整的代码:
public class SummonerInfoResponse extends HashMap< String,SummonerDto> {
}
并使用它:
return gson.fromJson(response,SummonerInfoResponse.class);
I am trying to parse the following response using gson in my android app:
{
"richerich":{
"id":19250176,
"name":"RichERich",
"profileIconId":744,
"summonerLevel":30,
"revisionDate":1425977347000
}
"alma":{
"id":19250174,
"name":"Alma",
"profileIconId":764,
"summonerLevel":30,
"revisionDate":14259773423424
}
}
The key "richeric" is a dynamic key and may change, and i can also have other response objects like "richeric" in my response string.
I create classes for this:
public class SummonerDto {
private long id;
private String name;
private int profileIconId;
private long revisionDate;
private long summonerLevel;
//getters, setters...
}
and my response class:
public class SummonerInfoResponse {
private Map<String, SummonerDto> summoners;
public Map<String, SummonerDto> getSummoners() {
return summoners;
}
public void setSummoners(Map<String, SummonerDto> summoners) {
this.summoners = summoners;
}
}
and i use the following piece of code:
return gson.fromJson(response, SummonerInfoResponse.class);
but it returns null. Can anyone tell me why?
Thanks.
I found the solution.
I extended my response class with HashMap and now i can get the response as a gson object. Here is the full code:
public class SummonerInfoResponse extends HashMap<String, SummonerDto> {
}
and use this:
return gson.fromJson(response, SummonerInfoResponse.class);
这篇关于gson.fromJson为动态键返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!