Jackson(一):常用注解说明

一、说明

名词声明:序列化指实体对象转json字符串;反序列化指json字符串转实体对象

1.@JsonInclude

用途:用于实体序列化为json字符串时,指示实体中符合条件的参与序列化的字段。
位置:类名上,即对该类的全部属性生效;属性上,即仅对该属性生效。
用法:@JsonInclude(Include.值)。
(仅说明几个常用的枚举值,其他的枚举值说明可以参考源码中的注释)

NON_NULL,仅序列化非null值的属性。
NON_EMPTY,仅序列化非空值的属性(包含null)。
NON_DEFAULT,仅序列化非默认初始值的属性。

2.@JsonIgnoreProperties

用途:如果json字段转换为实体类即反序列化的时候,有字段无法对应实体类即会报错json解析异常,使用此注解,可以忽略json字符串中与bean对象属性名对应不上的内容。
位置:类上。
用法
①@JsonIgnoreProperties({“属性名”,“属性名”}) :反序列化时忽略指定属性
②@JsonIgnoreProperties(ignoreUnknown = true) :反序列化时忽略未知属性

3.@JsonProperty

用途:在反序列化时,将json字符串中的字段与指定的属性对应转换;在序列化时,将对象的属性转换为指定字段名称。
位置:属性上。
用法:@JsonProperty(“定义json中的字段”)

二、示例

1.引入库

	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-core</artifactId>
		<version>${jackson.version}</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>${jackson.version}</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-annotations</artifactId>
		<version>${jackson.version}</version>
	</dependency>

2.操作

SkyLinkSerializer 是我自己封装的jackson工具类

@JsonInclude
实体类

@Getter
@Setter
@ToString
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Person {
    private int id;
    private String name;
}

测试结果

 @Test
  public void test07() throws SkyLinkException {
    SkyLinkSerializer se = new SkyLinkSerializer();
    Person p1 = new Person();
    p1.setId(12);
    System.out.println(se.encode(p1));
}

{"id":12}

@JsonIgnoreProperties
实体类

@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    private int id;
    private String name;
}

测试结果

  @Test
  public void test07() throws SkyLinkException {
    SkyLinkSerializer se = new SkyLinkSerializer();
    String p2 = "{" +
                 "\"id\":12," +
                 "\"ne\":\"www\"," +
                 "\"other\":\"cccc\"" +
                "}";
    System.out.println(se.decode(p2, Person.class));
  }
}

Person(id=12, name=null)

@JsonProperty
@JsonIgnoreProperties
实体类

@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    private int id;
    @JsonProperty("ne")
    private String name;
}

测试结果

  @Test
  public void test07() throws SkyLinkException {
    SkyLinkSerializer se = new SkyLinkSerializer();
    String p2 = "{" +
                 "\"id\":12," +
                 "\"ne\":\"www\"," +
                 "\"other\":\"cccc\"" +
                "}";
    System.out.println(se.decode(p2, Person.class));
  }
}

Person(id=12, name=www)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值