jackson的基本使用

jackson的基本使用

  • 导入maven依赖

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.11.2</version>
   </dependency>

1、java对象转json

@Test
public void test01() throws JsonProcessingException {
   //创建User对象
   User user=new User("admin","1111");
   //将user转为json格式
   ObjectMapper objectMapper=new ObjectMapper();
   String userString=objectMapper.writeValueAsString(user);
   System.out.println(userString);
}

2、writeValue(参数1,obj)方法介绍

  • 参数1

    • File:将obj对象转换为json字符串,并保存到指定的文件中

    • writer:将obj对象转换为json字符串,并将json数据填充到字符输出流中

    • Outputstream:将obj对象转换为json字符串,并将json数据填充到字节输出流中

3、注解介绍

  • @JsonIgnore:排除属性,即当前注解属性不转化json

  • @JsonFormat:属性值的格式化

    • 常用在日期属性上,eg:@sonFormat(pattern = "yyyy-MM-dd")

4、json转java对象

 @Test
public void test02() throws JsonProcessingException {
   //创建json对象
   String json="{"username":"admin","password":"1111"}";
   //将json对象转为java对象
   ObjectMapper objectMapper=new ObjectMapper();
   User user=objectMapper.readValue(json,User.class);
   System.out.println(user);
}

5、集合转json

@Test
public void test03() throws JsonProcessingException {
   //创建User对象
   User user=new User("admin","1111");
   //存储User对象
   List<User> userList=new ArrayList<User>();
   userList.add(user);
   userList.add(user);
   userList.add(user);
   //集合转json
   ObjectMapper objectMapper=new ObjectMapper();
   String listJson=objectMapper.writeValueAsString(userList);
   System.out.println(listJson);
}

注:map集合的转换和list是一样的

记得快乐
原文地址:https://www.cnblogs.com/Y-wee/p/13716234.html