背景
有个场景就是要把pojo转成map<String,Object>,用于展示,但是自己写的感觉太丑了,一个pojo就得写一个。
比如下面这样
image.png
想看看怎么改进
jackson的支持
参照refer,发现jackson是支持pojo和map互转的(之前只是看前辈用过,以为只是和json String互相转换用的,结果发现jackson功能太强大了,可以参照知乎的refer
pojo和map转换的demo
非常简单
public class Main {
static class Student {
@JsonIgnore
private String name;
@JsonIgnore
private int age;
private List<String> skills;
// getters setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getSkills() {
return skills;
}
public void setSkills(List<String> skills) {
this.skills = skills;
}
}
public static void main(String[] args) {
ObjectMapper oMapper = new ObjectMapper();
Student obj = new Student();
obj.setName("asd");
obj.setAge(34);
obj.setSkills(Arrays.asList("zxc","h"));
// object -> Map
Map<String, Object> map = oMapper.convertValue(obj, Map.class);
System.out.println(map);
}
}
输出如下
因为其他属性都被JsonIgnore了
{skills=[zxc, h]}
思考
后续可以看看jackson源码,不过现在rocketmq源码都block住了
refer
https://www.mkyong.com/java/java-convert-object-to-map-example/
https://stackoverflow.com/questions/35848506/how-to-convert-not-all-attributes-from-a-java-object-to-json-using-jackson-objec
https://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null 忽略属性值为null的
http://www.makeinjava.com/convert-list-objects-tofrom-json-java-jackson-objectmapper-example/ list和string互转
https://www.zhihu.com/question/44199956 和fastjson比较
http://vickyqi.com/2015/10/19/%E5%87%A0%E7%A7%8D%E5%B8%B8%E7%94%A8JSON%E5%BA%93%E6%80%A7%E8%83%BD%E6%AF%94%E8%BE%83/ 性能比较
http://jackson.codehaus.org/ 官网
https://github.com/FasterXML 源码
网友评论