【发布时间】:2018-03-13 14:43:19
【问题描述】:
团队我需要一种正确的方法来使用 Gson 将数据存储到 HashMap<> 中,因为我正在执行以下 Java 类,但是当我尝试从 HashMap<> 获取一些值时,我只是得到 NullPointerException 错误,当我尝试从Hashmap<> 中获取一些价值时,我成功地将 Json 获取到 Java 类,为什么我需要将它存储在 HashMap<> 中,因为对象名称非常随机,我无法为每个项目。
我尝试存储 JSON 数据的 Java 类:
public class Response {
private int id;
private String name;
private UserBean user;
private List<ItemsBean> items;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public UserBean getUser() {return user;}
public void setUser(UserBean user) {this.user = user;}
public List<ItemsBean> getItems() {return items;}
public void setItems(List<ItemsBean> items) {this.items = items;}
public static class UserBean {
private String name;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
public static class ItemsBean {
private HashMap<String, CodecBean> codec;
public HashMap<String, CodecBean> getCodec() {return codec;}
public void setCodec(HashMap<String, CodecBean> codec) {this.codec = codec;}
public static class CodecBean {
private int id;
private int strong;
private boolean active;
private String sell;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public int getStrong() {return strong;}
public void setStrong(int strong) {this.strong = strong;}
public boolean isActive() {return active;}
public void setActive(boolean active) {this.active = active;}
public String getSell() {return sell;}
public void setSell(String sell) {this.sell = sell;}
}
}}
JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [{
"987987M7812b163eryrt": {
"id": 1,
"strong": 456,
"active": true,
"sell": "te"
},
"90812bn120893juuh": {
"id": 2,
"strong": 4700,
"active": true,
"sell": "tt"
},
"981273jn19203nj123rg": {
"id": 3,
"strong": 3000,
"active": true,
"sell": "ti"
}
}]
}
我尝试以这种方式获取值:
Response.ItemsBean item = (Response.ItemsBean) getItem(i);
TextView txt;
txt.setText(item.getCodec().get(i).getSell());
你能告诉我我做错了什么吗?
提前致谢
【问题讨论】:
-
你已被标记...这将是很好的禁令...
-
您要保存数据吗?
-
@Nasimxon 是的,我需要在 HashMap 中保存“项目”
-
@Selvin 你为什么这么说?