Jackson基础使用手册

1、对象转json字符串

复制代码
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] arges) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person("jackson",20);
        System.out.println(mapper.writeValueAsString(person));
    }
}
复制代码

1.1、使用字段别名

  @JsonProperty("userName")
    private String name;

1.2、@JsonIgnore注解使用

@JsonIgnore注解是在序列化时忽略该字段

    @JsonIgnore
    @JsonProperty("userName")
    private String name;
    @JsonProperty("userAge")
    private Integer age;

1.3、@JsonFormat注解格式化日期格式

    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss:SSS",timezone="GMT+8")
    private Date date;

1.4、JavaType

1.4.1、如果为Map类型

mapper.getTypeFactory().constructParametricType(Map.class,String.class,Student.class);

第二个参数是Map的key,第三个参数是Map的value

1.4.2、如果为List类型

personList  =  mapper.readValue(mapper.writeValueAsString(personList),mapper.getTypeFactory().constructParametricType(List.class,Person.class));

1.5、TypeReference

TypeReference比javaType模式更加方便,代码也更加简洁

mapper.readValue(json, new TypeReference<List<Person>>(){}); 

2、json字符串转对象

ObjectMapper mapper = new ObjectMapper();
Person person = new Person("jackson",20,175);
System.out.println(mapper.writeValueAsString(person));
//mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
System.out.println(mapper.readValue("{\"sheight\":172}", Person.class));

 

posted @   浅笑19  阅读(134)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示