Json注解属性JsonIgnoreProperties,JsonInclude,JsonProperty总结小记

本文介绍了三种常用的JSON注解:@JsonIgnoreProperties用于忽略类中不存在的字段;@JsonInclude用于忽略值为null的字段;@JsonProperty用于指定返回前端的字段名称。

1.JsonIgnoreProperties属性
示例用法:@JsonIgnoreProperties(ignoreUnknown = true)
该注解是放在类名上面,作用是:忽略类中不存在的字段当接收的时候

2.JsonInclude属性
示例用法:@JsonInclude(JsonInclude.Include.NON_NULL)
该注解也是放在类名上面,作用是:忽略类中字段值为null的当接收的时候

3.JsonProperty属性
示例用法:@JsonProperty(“element_type”)
该注解是放在字段上面,作用是:当返回前端时字段为element_type(注解里定义的属性)

在Java中,`@JsonProperty` 是 Jackson 库中的一个注解,用于将 JSON 字段映射到 Java 对象的属性上。以下是在 JSON 类中使用 `@JsonProperty` 的方法: ### 为属性映射不同的 JSON 字段名 当 JSON 字符串的某个字段名 Java 类的属性名不一致时,可以使用 `@JsonProperty` 将 JSON 字段映射到 Java 类的属性上。示例代码如下: ```java import com.fasterxml.jackson.annotation.JsonProperty; public class MyClass { // 将 JSON 中的 "FModel" 字段映射到该属性 @JsonProperty(value = "FModel") private String model; public String getModel() { return model; } public void setModel(String model) { this.model = model; } } ``` 上述代码中,通过在 `model` 属性上添加 `@JsonProperty(value = "FModel")` 注解,实现了将 JSON 字符串中的 `"FModel"` 字段的值赋给 Java 对象的 `model` 属性 [^2]。 ### 指定属性JSON 中的顺序 `@JsonProperty` 注解中的 `index` 属性可以指定属性JSON 中的顺序。示例代码如下: ```java import com.fasterxml.jackson.annotation.JsonProperty; public class Person { // 指定该属性JSON 中的顺序为 1 @JsonProperty(index = 1) private String firstName; // 指定该属性JSON 中的顺序为 0 @JsonProperty(index = 0) private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } ``` 上述代码中,`lastName` 属性的 `index` 为 0,`firstName` 属性的 `index` 为 1,因此在生成的 JSON 中,`lastName` 会排在 `firstName` 前面 [^3]。 ### 解决不同语言命名规范差异 由于不同语言对于变量命名规则要求不一致,在使用 JSON 承接数据时,可以使用 `@JsonProperty` 做字段映射,以符合代码规范。示例代码如下: ```java import com.fasterxml.jackson.annotation.JsonProperty; public class MyModel { // 将对方的大驼峰命名的字段映射到小驼峰命名的属性 @JsonProperty("BigCamelCaseField") private String bigCamelCaseField; public String getBigCamelCaseField() { return bigCamelCaseField; } public void setBigCamelCaseField(String bigCamelCaseField) { this.bigCamelCaseField = bigCamelCaseField; } } ``` 上述代码中,通过 `@JsonProperty` 注解将对方使用大驼峰命名的 `"BigCamelCaseField"` 字段映射到 Java 类中使用小驼峰命名的 `bigCamelCaseField` 属性,以符合 Java 的命名规范 [^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值