11

JSON数据处理框架Jackson精解第一篇-序列化与反序列化核心用法

 3 years ago
source link: https://segmentfault.com/a/1190000024486513
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ZZ3yEb7.png!mobile

Jackson是Spring Boot默认的JSON数据处理框架,但是其并不依赖于任何的Spring 库。有的小伙伴以为Jackson只能在Spring框架内使用,其实不是的,没有这种限制。它提供了很多的JSON数据处理方法、注解,也包括 流式API、树模型、数据绑定 ,以及复杂数据类型转换等功能。它虽然简单易用,但绝对不是小玩具,本节为大家介绍Jackson的基础核心用法, 更多的内容我会写成一个系列,5-10篇文章,请您继续关注我。

一、基础准备

在任意项目中引入下面的jar就可以使用jackson进行JSON的数据序列化与反序列化的功能。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

写一个PlayerStar的实体类,实体类主要体现篮球明星的名字、年龄、业余爱好、朋友、年收入等信息,为了尽可能地演示Jackson的序列化与反序列化功能,将数组、List、Map都融合到这个类里面。并通过getInstance初始化篮球明星Jordan这个对象。

@Data
public class PlayerStar {

  private String name;
  private Integer age;
  private String[] hobbies;    //业余爱好,数组
  private List<String> friends;   //  朋友
  private Map<String, BigDecimal> salary; //年收入 Map


  //初始化一个对象用于测试
  public static PlayerStar getInstance(){
    PlayerStar playerStar = new PlayerStar();

    playerStar.setName("乔丹");
    playerStar.setAge(45);
    playerStar.setHobbies(new String[]{"高尔夫球", "棒球"});
    Map<String, BigDecimal> salary = new HashMap<String, BigDecimal>() {{
      put("2000", new BigDecimal(10000000));
      put("2010", new BigDecimal(62000000));
      put("2020", new BigDecimal(112400000));
    }};
    playerStar.setSalary(salary);
    playerStar.setFriends(Arrays.asList("kobe", "curry", "james"));

    return playerStar;
  }

}

二、序列化方法

下面代码演示了如何将PlayerStar对象序列化为JSON字符串。

  • writeValue可以接收File作为参数,将JSON序列化结果保存到文件中
  • writeValueAsString将JSON序列化结果以String形式返回
  • writerWithDefaultPrettyPrinter方法可以将JSON序列化结果进行格式化,更好的显示结构,易于查看
@Test
void testObject2JSON() throws IOException {
  //获取对象实例
  PlayerStar player = PlayerStar.getInstance();

  //ObjectMapper作为Jackson的API工具类存在
  ObjectMapper mapper = new ObjectMapper();
  //将player对象以JSON格式进行序列化,并将序列化结果写入文件
  mapper.writeValue(new File("d:\\data\\jackson\\player.json"), player);

  //将player对象以JSON格式进行序列化为String对象
  String jsonString = mapper.writeValueAsString(player);
  System.out.println(jsonString);

  //将player对象以JSON格式进行序列化为String对象(格式美化)
  String jsonInString2 = mapper.writerWithDefaultPrettyPrinter()
          .writeValueAsString(player);
  System.out.println(jsonInString2);
}

jsonString的控制台打印输出结果,也是d:\data\jackson\player.json文件的内容

{"name":"乔丹","age":45,"hobbies":["高尔夫球","棒球"],"friends":["kobe","curry","james"],"salary":{"2000":10000000,"2010":62000000,"2020":112400000}}

jsonString2的控制台打印输出,格式进行了美化,因为使用了writerWithDefaultPrettyPrinter()方法

{
  "name" : "乔丹",
  "age" : 45,
  "hobbies" : [ "高尔夫球", "棒球" ],
  "friends" : [ "kobe", "curry", "james" ],
  "salary" : {
    "2000" : 10000000,
    "2010" : 62000000,
    "2020" : 112400000
  }
}

三、反序列化方法

下面代码演示了如何将JSON字符串反序列化为Java对象

@Test
void testJSON2Object() throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  //从文件中读取JSON字符串,反序列化为java对象
  PlayerStar player = mapper.readValue(new File("d:\\data\\jackson\\player.json"), PlayerStar.class);
  System.out.println(player);

  //将JSON字符串反序列化为java对象
  String jsonInString = "{\"name\":\"乔丹\",\"age\":45,\"hobbies\":[\"高尔夫球\",\"棒球\"]}";
  PlayerStar jordan = mapper.readValue(jsonInString, PlayerStar.class);

  System.out.println(jordan);

}

PlayerStar对象控制台输出结果如下( 注意这里的输出不是JSON格式,而是java对象的toString()方法值 ):

PlayerStar(name=乔丹, age=45, hobbies=[高尔夫球, 棒球], friends=[kobe, curry, james], salary={2000=10000000, 2010=62000000, 2020=112400000})
PlayerStar(name=乔丹, age=45, hobbies=[高尔夫球, 棒球], friends=null, salary=null)

四、字段重命名 @JsonProperty

可以使用 @JsonProperty来影响序列化和反序列化对象属性的重命名。

@Data
public class PlayerStar {

  @JsonProperty("playerName")
  private String name;  //将属性name序列化为playerName,同时影响反序列化

使用上面代码的注解之后,JSON序列化的结果name属性变成playerName属性

{"playerName":"乔丹"  ……

同时影响反序列化,下面的反序列化代码会报错,因为使用了name属性。应该使用playerName才可以。

String jsonInString = "{\"name\":\"乔丹\",\"age\":45,\"hobbies\":[\"高尔夫球\",\"棒球\"]}";
PlayerStar jordan = mapper.readValue(jsonInString, PlayerStar.class);

五、忽略null字段的序列化 @JsonInclude

当我们不为对象的成员变量赋值的时候,默认情况下,Jackson的序列化结果是下面的这样的。

{
  "age" : 45,
  "hobbies" : null,
  "friends" : null,
  "salary" : null,
  "playerName" : "乔丹"
}

如果我们不希望将null值,体现在JSON序列化结果中,我们可以使用下面的方法。如果希望在某次序列化的全局范围内,忽略null成员变量,可以使用下面的API

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

或者是在类名的上面加上如下注解。该注解将针对类里面的所有成员变量生效,只要成员变量为null,将不会被包含在序列化结果中。

@JsonInclude(JsonInclude.Include.NON_NULL)
public class PlayerStar {
   ......
}

如果我们想针对PlayerStar类里面某些成员变量单独忽略null,可以在成员变量上面加注解。

@JsonInclude(JsonInclude.Include.NON_NULL)
private String[] hobbies;    //业余爱好,数组
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<String> friends;   //  朋友
@JsonInclude(JsonInclude.Include.NON_NULL)
private Map<String, BigDecimal> salary; //年收入 Map

忽略为null的成员变量后,JSON序列化结果是下面这样的

{
  "age" : 45,
  "playerName" : "乔丹"
}

六、忽略指定的字段

默认情况下,jackson不会将static和transient的成员变量进行序列化与反序列化操作。我们还可以通过

@JsonIgnore
@JsonIgnoreProperties

上面的两种注解选其一即可,下面的代码两种注解我都用了,功能是重复的

@Data
@JsonIgnoreProperties({"hobbies", "friends","salary"})
public class PlayerStar {

  @JsonProperty("playerName")
  private String name;
  private Integer age;

  @JsonIgnore
  private String[] hobbies;    //业余爱好,数组
  @JsonIgnore
  private List<String> friends;   //  朋友
  @JsonIgnore
  private Map<String, BigDecimal> salary; //年收入 Map

......

在类或成员变量上面加上注解之后,序列化结果如下,指定字段被忽略。

{
  "age" : 45,
  "playerName" : "乔丹"
}

需要注意的是这两个注解不只是影响序列化为JSON字符串的过程,也影响JSON字符串反序列化为java对象的过程。举例:如果JSON字符串包含了类中被JsonIgnore的属性值hobbies,不会被反序列化赋值给java对象的成员变量hobbies。

欢迎关注我的博客,里面有很多精品合集

  • 本文转载注明出处(必须带连接,不能只转文字): 字母哥博客

觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力!。另外,笔者最近一段时间输出了如下的精品内容,期待您的关注。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK