【发布时间】:2020-08-09 07:02:43
【问题描述】:
我的转换代码:
public MyEntity convert(){
HashMap<String,String> map = new HashMap<>();
map.put("name","akshay");
map.put("mobile","xxxxxxx");
map.put("soap","lux");
map.put("noodles","maggi");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
MyEntity pojo = gson.fromJson(jsonElement, MyEntity.class);
System.out.println(gson.toJson(pojo));
return pojo;
}
我的实体类:
public class MyEntity {
private String name;
private int mobile;
private HashMap<String,String> utility;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMobile() {
return mobile;
}
public void setMobile(int mobile) {
this.mobile = mobile;
}
public HashMap<String, String> getUtility() {
return utility;
}
public void setUtility(HashMap<String, String> utility) {
this.utility = utility;
}
}
我使用我的代码得到了什么:
{
"name" : "akshay",
"mobile" : 1234567890
}
但我想要这样的输出:
{
"name" : "akshay",
"mobile" : 1234567890,
"utility" : {
"soap" : "lux",
"noodles" : "maggi"
}
}
GSON 没有映射 SOAP 和面条,因为 POJO 中没有对应的匹配对象。这就是我采用 hashmap 的原因。我希望 GSON 将所有不匹配的字段放入哈希图中。
实用程序下的键值对不固定的一个值得注意的事情取决于客户购买。我的意思是它可能是下面这样的其他东西。
{
"name" : "akshay",
"mobile" : 1234567890,
"utility" : {
"toothpaste" : "colgate",
"noodles" : "maggi"
}
}
【问题讨论】:
-
顺便说一句,成员变量应该是
private。 -
好的,谢谢,我会编辑代码