java - 使用 GSON 或 Jackson 到 POJO 的 HashMap
问题描述
我的转换代码:
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"
}
}
解决方案
这可以解决问题:
HashMap<String, Object> map = new HashMap<>();
map.put("name", "akshay");
map.put("mobile", "xxxxxxx");
HashMap<String, String> utility = new HashMap<>();
utility.put("soap", "lux");
utility.put("noodles", "maggi");
map.put("utility", utility);
GSON 忽略肥皂和面条,因为它们不在正确的水平上。他们需要成为“效用”的孩子。
如果您希望以您所描述的特定方式解析“平面” JSON 结构(匹配字段以 1:1 映射,不匹配字段进入实用程序),您可以编写自定义(反)序列化程序。有关示例,请参见此问题:GSON - Custom serializer in specific case。但是,我不建议这样做,因为它可能最终需要更多的工作。
推荐阅读
- counter - Add() 在 Java 中不起作用(Greenfoot)
- javascript - HTML5 File API - 使用 PHP 将 blob 保存到文件
- javascript - JavaScript 中的井字游戏获胜条件
- .net - Incapsula 阻止包含危险标签的 HTML 上传文件
- ios - 更改语言后如何强制用户重新启动应用程序
- assembly - 汇编任务:翻译
- python - 如何在 django 中实现多级管理?
- python - 在 Jupyter Lab 笔记本中使用 PyMongo 不会关闭与 MongoDB 服务器的任何连接
- html - 在浮动 div 周围环绕文本(和图像)
- html - 如何始终将我的页脚设置在底部是否可以仅使用 css