ToB企服应用市场:ToB评测及商务社交产业平台

标题: Java jackson常用注解汇总 [打印本页]

作者: 河曲智叟    时间: 2023-12-10 12:34
标题: Java jackson常用注解汇总
提起 jackson,在日常使用中,由于涉及到各种序列化和反序列化的处理,就不能不提 注解,了解注解的常用方式可以极大地方便我们处理序列化,今天分享一些在使用 jackson 中涉及到的注解。

目录

1.@JsonProperty - 字段命名

@JsonProperty 注解用于在序列化时按照给定的字段名命名,在反序列化时,在 json 串中的注解字段给该字段设置属性值。
下面是注解的简单示例:
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. public class PersonProperty {
  4.     @JsonProperty("first_name")
  5.     private String firstName;
  6.     public PersonProperty() {
  7.     }
  8.     public String getFirstName() {
  9.         return firstName;
  10.     }
  11.     public void setFirstName(String firstName) {
  12.         this.firstName = firstName;
  13.     }
  14. }
  15. ---
  16. public static void jsonPropertyDemo() {
  17.     ObjectMapper objectMapper = new ObjectMapper();
  18.     PersonProperty pp = new PersonProperty();
  19.     pp.setFirstName("Alice");
  20.     String jsonString = null;
  21.     try {
  22.         jsonString = objectMapper.writeValueAsString(pp);
  23.         System.out.println("json property: " + jsonString);
  24.     } catch (Exception e) {
  25.         e.printStackTrace();
  26.     }
  27.     try {
  28.         PersonProperty pp1 = objectMapper.readValue(jsonString, PersonProperty.class);
  29.         System.out.println(pp1.getFirstName());
  30.     } catch (Exception e) {
  31.         e.printStackTrace();
  32.     }
  33. }
  34. ---
复制代码
2.@JsonPropertyOrder - 字段序列化顺序

@JsonPropertyOrder加在类上,用以规定数据序列化时字段出现的顺序。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonPropertyOrder;
  3. // {"name":"Bob","id":"111","age":25,"phone":"12345678910"}
  4. @JsonPropertyOrder({"name", "id", "age", "phone"})
  5. // 没有定义顺序,就按照字典序排列,{"age":25,"id":"111","name":"Bob","phone":"12345678910"}
  6. // @JsonPropertyOrder(alphabetic = true)
  7. public class PersonPropertyOrder {
  8.     private String id;
  9.     private String name;
  10.     private int age;
  11.     private String phone;
  12.     public PersonPropertyOrder() {
  13.     }
  14.     public String getId() {
  15.         return id;
  16.     }
  17.     public void setId(String id) {
  18.         this.id = id;
  19.     }
  20.     public String getName() {
  21.         return name;
  22.     }
  23.     public void setName(String name) {
  24.         this.name = name;
  25.     }
  26.     public int getAge() {
  27.         return age;
  28.     }
  29.     public void setAge(int age) {
  30.         this.age = age;
  31.     }
  32.     public String getPhone() {
  33.         return phone;
  34.     }
  35.     public void setPhone(String phone) {
  36.         this.phone = phone;
  37.     }
  38. }
  39. ---
  40. public static void jsonPropertyOrder() {
  41.     ObjectMapper objectMapper = new ObjectMapper();
  42.     PersonPropertyOrder ppo = new PersonPropertyOrder();
  43.     ppo.setAge(25);
  44.     ppo.setId("111");
  45.     ppo.setName("Bob");
  46.     ppo.setPhone("12345678910");
  47.     String jsonString = null;
  48.     try {
  49.         jsonString = objectMapper.writeValueAsString(ppo);
  50.         System.out.println("json property: " + jsonString);
  51.     } catch (Exception e) {
  52.         e.printStackTrace();
  53.     }
  54. }
  55. ---
复制代码
3.@JsonAlias - 字段别名,反序列化

在数据反序列化时,通过 @JsonAlias 注解来设置字段的值,只要是 alias中的和字段本身都可以正常反序列化。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonAlias;
  3. public class PersonAlias {
  4.     @JsonAlias({"firstName", "personName"})
  5.     private String name;
  6.     public PersonAlias() {
  7.     }
  8.     public String getName() {
  9.         return name;
  10.     }
  11.     public void setName(String name) {
  12.         this.name = name;
  13.     }
  14. }
  15. ---
  16. public static void jsonAlias() {
  17.     String jsonString1 = "{"name":"Bob"}";
  18.     String jsonString2 = "{"firstName":"Bob"}";
  19.     String jsonString3 = "{"personName":"Bob"}";
  20.     ObjectMapper objectMapper = new ObjectMapper();
  21.     try {
  22.         PersonAlias p1 = objectMapper.readValue(jsonString1, PersonAlias.class);
  23.         PersonAlias p2 = objectMapper.readValue(jsonString2, PersonAlias.class);
  24.         PersonAlias p3 = objectMapper.readValue(jsonString3, PersonAlias.class);
  25.         System.out.printf("p1: %s, p2: %s, p3: %s", p1.getName(),p2.getName(), p3.getName());
  26.     } catch (Exception e) {
  27.         e.printStackTrace();
  28.     }
  29. }
  30. ---
复制代码
4.@JsonIgnore -序列化时忽略字段

@JsonIgnore 加在字段上,用以在序列化时,忽略其,在反序列化时,仅赋值null。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonIgnore;
  3. public class PersonIgnore {
  4.     private String name;
  5.     @JsonIgnore // 不将其序列化,忽略该字段
  6.     private String[] hobbies;
  7.     public PersonIgnore() {
  8.     }
  9.     public String getName() {
  10.         return name;
  11.     }
  12.     public void setName(String name) {
  13.         this.name = name;
  14.     }
  15.     public String[] getHobbies() {
  16.         return hobbies;
  17.     }
  18.     public void setHobbies(String[] hobbies) {
  19.         this.hobbies = hobbies;
  20.     }
  21. }
  22. ---
  23. public static void jsonIgnore() {
  24.     ObjectMapper objectMapper = new ObjectMapper();
  25.     String jsonString = null;
  26.     try {
  27.         PersonIgnore pi = new PersonIgnore();
  28.         pi.setName("Cathy");
  29.         pi.setHobbies(null);
  30.         jsonString = objectMapper.writeValueAsString(pi);
  31.         System.out.println(jsonString);
  32.     } catch (Exception e) {
  33.         e.printStackTrace();
  34.     }
  35. }   
  36. ---
复制代码
5.@JsonIgnoreProperties - 序列化时忽略某些字段

@JsonIgnoreProperties 加在类上,用于在序列化时,忽略给定的某些字段。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  3. @JsonIgnoreProperties({"age"})
  4. public class PersonIgnoreProperties {
  5.     private String name = "Alice";
  6.     private int age;
  7.     public PersonIgnoreProperties() {
  8.     }
  9.     public String getName() {
  10.         return name;
  11.     }
  12.     public void setName(String name) {
  13.         this.name = name;
  14.     }
  15.     public int getAge() {
  16.         return age;
  17.     }
  18.     public void setAge(int age) {
  19.         this.age = age;
  20.     }
  21. }
  22. ---
  23. public static void jsonIgnoreProperties() {
  24.     ObjectMapper objectMapper = new ObjectMapper();
  25.     PersonIgnoreProperties pip = new PersonIgnoreProperties();
  26.     pip.setName("Bob");
  27.     pip.setAge(18);
  28.     try {
  29.         String jsonString = objectMapper.writeValueAsString(pip);
  30.         System.out.println(jsonString);
  31.     } catch (Exception e) {
  32.         e.printStackTrace();
  33.     }
  34. }
  35. ---
复制代码
6.@JsonInclude - 序列化时作用于满足条件的

@JsonInclude可以加在类上,也可以加在字段上。该注解表示满足某些条件(
NON_NULL,
NON_ABSENT,
NON_EMPTY,
NON_DEFAULT,
等)的才能序列化,e.g.如果加在类上,表示只要对象有null 就忽略该对象,加在字段上,如果字段是null,则忽略该字段。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonInclude;
  3. @JsonInclude(JsonInclude.Include.NON_NULL)
  4. public class PersonInclude {
  5.     private int id;
  6.     private String name;
  7.     @JsonInclude(JsonInclude.Include.NON_NULL)
  8.     private String[] hobbies;
  9.     public PersonInclude() {
  10.     }
  11.     public int getId() {
  12.         return id;
  13.     }
  14.     public void setId(int id) {
  15.         this.id = id;
  16.     }
  17.     public String getName() {
  18.         return name;
  19.     }
  20.     public void setName(String name) {
  21.         this.name = name;
  22.     }
  23.     public String[] getHobbies() {
  24.         return hobbies;
  25.     }
  26.     public void setHobbies(String[] hobbies) {
  27.         this.hobbies = hobbies;
  28.     }
  29. }
  30. ---
  31. public static void jsonInclude() {
  32.     ObjectMapper objectMapper = new ObjectMapper();
  33.     PersonInclude pi = new PersonInclude();
  34.     pi.setName("Cathy");
  35.     pi.setId(1111);
  36.     try {
  37.         String jsonString = objectMapper.writeValueAsString(pi);
  38.         System.out.println(jsonString);
  39.     } catch (Exception e) {
  40.         e.printStackTrace();
  41.     }
  42. }
  43. ---
复制代码
7.@JsonFormat - 设置格式,如日期时间等

用于设置时间格式,或者是数字,或者是日期格式。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonFormat;
  3. import java.time.LocalDate;
  4. import java.util.Date;
  5. public class PersonFormat {
  6.     @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss", timezone = "GMT+8")
  7.     private Date birthDate;
  8.     public PersonFormat() {
  9.     }
  10.     public Date getBirthDate() {
  11.         return birthDate;
  12.     }
  13.     public void setBirthDate(Date birthDate) {
  14.         this.birthDate = birthDate;
  15.     }
  16. }
  17. ---
  18. public static void jsonFormat() {
  19.     ObjectMapper objectMapper = new ObjectMapper();
  20.     PersonFormat pf = new PersonFormat();
  21.     pf.setBirthDate(new Date());
  22.     try {
  23.         String jsonString = objectMapper.writeValueAsString(pf);
  24.         System.out.println(jsonString);
  25.     } catch (Exception e) {
  26.         e.printStackTrace();
  27.     }
  28. }
  29. ---
复制代码
8.@JacksonInject - 反序列化时注入到 java 对象

该注解用于在数据反序列化时将其他字段注入进 Java对象。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JacksonInject;
  3. import java.time.LocalDate;
  4. import java.time.LocalDateTime;
  5. public class PersonInject {
  6.     private String name;
  7.    
  8.     private int age;
  9.    
  10.     @JacksonInject("responseTime")
  11.     private LocalDateTime responseTime;
  12.     public PersonInject() {
  13.     }
  14.     public String getName() {
  15.         return name;
  16.     }
  17.     public void setName(String name) {
  18.         this.name = name;
  19.     }
  20.     public int getAge() {
  21.         return age;
  22.     }
  23.     public void setAge(int age) {
  24.         this.age = age;
  25.     }
  26.     public LocalDateTime getResponseTime() {
  27.         return responseTime;
  28.     }
  29.     public void setResponseTime(LocalDateTime responseTime) {
  30.         this.responseTime = responseTime;
  31.     }
  32. }
  33. ---
  34. public static void jsonInject() {
  35.     InjectableValues.Std iv = new InjectableValues.Std();
  36.     ObjectMapper objectMapper = new ObjectMapper();
  37.     iv.addValue("responseTime", LocalDateTime.now());
  38.     //将JSON字符串反序列化为java对象
  39.     String jsonString = "{"name":"Alice","age":23}";
  40.     objectMapper.setInjectableValues(iv);
  41.     try {
  42.         PersonInject pi = objectMapper.readValue(jsonString, PersonInject.class);
  43.         System.out.println(pi.getResponseTime());
  44.     } catch (Exception e) {
  45.         e.printStackTrace();
  46.     }
  47. }
  48. ---
复制代码
9.@JsonCreator && @ConstructorProperties - 反序列化时采用的构造方法

@JsonCreator 用于在json数据反序列化到实例对象时采用哪个构造方法,同时搭配 @JsonProperty 注解用于相关属性的。
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonCreator;
  3. import com.fasterxml.jackson.annotation.JsonProperty;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. public class PersonCreator {
  6.     private String name;
  7.     private int age;
  8.     // 构造方法1
  9.     public PersonCreator(String name) {
  10.         this.name = name;
  11.     }
  12.     // 构造方法2
  13.     @JsonCreator // 用于反序列化时的处理
  14.     public PersonCreator(@JsonProperty("username") String name,
  15.                          @JsonProperty("age") int age) {
  16.         this.name = name;
  17.         this.age = age;
  18.     }
  19.     @Override
  20.     public String toString() {
  21.         return "Test{" +
  22.                 "name='" + name + ''' +
  23.                 ", age='" + age + ''' +
  24.                 '}';
  25.     }
  26.     public static void main(String[] args) throws Exception {
  27.         String jsonString = "{"username": "Alice", "age": 18}"; // username -> name
  28.         ObjectMapper objectMapper = new ObjectMapper();
  29.         try {
  30.             PersonCreator pc = objectMapper.readValue(jsonString, PersonCreator.class);
  31.             System.out.println(pc);
  32.         } catch (Exception e) {
  33.             e.printStackTrace();
  34.         }
  35.     }
  36. }
复制代码
@ConstructorProperties 也用于构造方法,但相比 @JsonCreator 的使用要简单,可以认为 @ConstructorProperties = @JsonCreator + @JsonProperty。
  1. package org.example;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import java.beans.ConstructorProperties;
  4. public class PersonConstructorProperties {
  5.     private String username;
  6.     private int age;
  7.     public PersonConstructorProperties(String username) {
  8.         this.username = username;
  9.     }
  10.     @ConstructorProperties({"name", "age"})
  11.     public PersonConstructorProperties(String username, int age) {
  12.         System.out.println("全参构造函数...");
  13.         this.username = username;
  14.         this.age = age;
  15.     }
  16.     @Override
  17.     public String toString() {
  18.         return "Test{" +
  19.                 "username='" + username + ''' +
  20.                 ", age='" + age + ''' +
  21.                 '}';
  22.     }
  23.     public static void main(String[] args) {
  24.         String jsonString = "{"name": "Bob", "age": 29}";
  25.         ObjectMapper objectMapper = new ObjectMapper();
  26.         try {
  27.             PersonConstructorProperties pcp = objectMapper.readValue(jsonString, PersonConstructorProperties.class);
  28.             System.out.println(pcp);
  29.         } catch (Exception e) {
  30.             e.printStackTrace();
  31.         }
  32.     }
  33. }
复制代码
10.@JsonSerialize && @JsonDeserialize - 自定义序列化方法

这两个注解用于实现自定义的序列化和反序列化的处理,比如我们有个需求,需要将小数的某个字段规定精确位数,为空时输出空字符串。
@JsonSerialize
  1. package org.example;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.databind.JsonSerializer;
  4. import com.fasterxml.jackson.databind.SerializerProvider;
  5. import com.fasterxml.jackson.databind.annotation.JsonSerialize;
  6. import java.io.IOException;
  7. import java.math.RoundingMode;
  8. import java.text.DecimalFormat;
  9. public class PersonSerialize {
  10.     @JsonSerialize(using = CustomDoubleSerialize.class, nullsUsing = NullNumberSerialize.class)
  11.     private Double model;
  12.     @JsonSerialize(nullsUsing = NullNumberSerialize.class)
  13.     private Double business;
  14.     private String name;
  15.     public PersonSerialize() {
  16.     }
  17.     public Double getModel() {
  18.         return model;
  19.     }
  20.     public void setModel(Double model) {
  21.         this.model = model;
  22.     }
  23.     public Double getBusiness() {
  24.         return business;
  25.     }
  26.     public void setBusiness(Double business) {
  27.         this.business = business;
  28.     }
  29.     public String getName() {
  30.         return name;
  31.     }
  32.     public void setName(String name) {
  33.         this.name = name;
  34.     }
  35. }
  36. /**
  37. * Double保留4位小数,输出string
  38. */
  39. class CustomDoubleSerialize extends JsonSerializer<Double> {
  40.     private static final DecimalFormat df = new DecimalFormat("#.####");
  41.     @Override
  42.     public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  43.         df.setRoundingMode(RoundingMode.HALF_UP); // 4
  44.         gen.writeString(df.format(value));
  45.     }
  46. }
  47. /**
  48. * 任意类型null值,改为空字符串输出
  49. */
  50. class NullNumberSerialize extends JsonSerializer<Object> {
  51.     @Override
  52.     public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  53.         gen.writeString("");
  54.     }
  55. }
  56. ---
  57. public static void jsonSerialize() {
  58.     ObjectMapper objectMapper = new ObjectMapper();
  59.     PersonSerialize ps = new PersonSerialize();
  60.     ps.setName("Alice");
  61.     ps.setModel(1.2345678);
  62.     try {
  63.         String jsonString = objectMapper.writeValueAsString(ps);
  64.         System.out.println(jsonString); // {"model":"1.2346","business":"","name":"Alice"}
  65.     } catch (Exception e) {
  66.         e.printStackTrace();
  67.     }
  68. }
  69. ---
复制代码
@JsonDeserialize
  1. package org.example;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.core.JsonParser;
  4. import com.fasterxml.jackson.databind.DeserializationContext;
  5. import com.fasterxml.jackson.databind.JsonDeserializer;
  6. import com.fasterxml.jackson.databind.JsonSerializer;
  7. import com.fasterxml.jackson.databind.SerializerProvider;
  8. import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
  9. import com.fasterxml.jackson.databind.annotation.JsonSerialize;
  10. import java.io.IOException;
  11. import java.time.LocalDateTime;
  12. import java.time.format.DateTimeFormatter;
  13. import java.time.format.FormatStyle;
  14. public class PersonDeserialize {
  15.     @JsonSerialize(using = LocalDatetimeSerialize.class)
  16.     @JsonDeserialize(using = LocalDatetimeDeserialize.class)
  17.     private LocalDateTime birthDate;
  18.     private String name;
  19.     public PersonDeserialize() {
  20.     }
  21.     public LocalDateTime getBirthDate() {
  22.         return birthDate;
  23.     }
  24.     public void setBirthDate(LocalDateTime birthDate) {
  25.         this.birthDate = birthDate;
  26.     }
  27.     public String getName() {
  28.         return name;
  29.     }
  30.     public void setName(String name) {
  31.         this.name = name;
  32.     }
  33. }
  34. class LocalDatetimeSerialize extends JsonSerializer<LocalDateTime> {
  35.     static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
  36.     @Override
  37.     public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
  38.         String str = value.format(DATE_FORMATTER);
  39.         gen.writeString(str);
  40.     }
  41. }
  42. class LocalDatetimeDeserialize extends JsonDeserializer<LocalDateTime> {
  43.     @Override
  44.     public LocalDateTime deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
  45.         String str = p.getText();
  46.         return LocalDateTime.parse(str, LocalDatetimeSerialize.DATE_FORMATTER);
  47.     }
  48. }
  49. ---
  50. public static void jsonDeserialize() {
  51.     ObjectMapper objectMapper = new ObjectMapper();
  52.     PersonDeserialize pd = new PersonDeserialize();
  53.     pd.setName("Dav");
  54.     pd.setBirthDate(LocalDateTime.of(2000, 12, 5, 0, 0));
  55.     String jsonString = null;
  56.     // serialize
  57.     try {
  58.         jsonString = objectMapper.writeValueAsString(pd);
  59.         System.out.println(jsonString); // {"birthDate":"2000年12月5日 00:00:00","name":"Dav"}
  60.     } catch (Exception e) {
  61.         e.printStackTrace();
  62.     }
  63.     // deserialize
  64.     try {
  65.         PersonDeserialize pd1 = objectMapper.readValue(jsonString, PersonDeserialize.class);
  66.         // person -> name: Dav, birthdate: 2000-12-05T00:00
  67.         System.out.printf("person -> name: %s, birthdate: %s\n", pd1.getName(), pd1.getBirthDate());
  68.     } catch (Exception e) {
  69.         e.printStackTrace();
  70.     }
  71. }
  72. ---
复制代码
11.@JsonAnyGetter && @JsonANySetter - 序列化对map字段的处理

这两个注解用于在序列化和反序列化时 map 结构的处理,具体说来:
  1. package org.example;
  2. import com.fasterxml.jackson.annotation.JsonAnyGetter;
  3. import com.fasterxml.jackson.annotation.JsonAnySetter;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class PersonGetAndSet {
  7.     private String username;
  8.     private String pwd;
  9.     private int age;
  10.     // @JsonAnySetter // 加方法或者属性都可以,但1个即可
  11.     private Map<String, String> map;
  12.     public PersonGetAndSet() {
  13.         this.map = new HashMap<>();
  14.     }
  15.     public String getUsername() {
  16.         return username;
  17.     }
  18.     public void setUsername(String username) {
  19.         this.username = username;
  20.     }
  21.     public String getPwd() {
  22.         return pwd;
  23.     }
  24.     public void setPwd(String pwd) {
  25.         this.pwd = pwd;
  26.     }
  27.     public int getAge() {
  28.         return age;
  29.     }
  30.     public void setAge(int age) {
  31.         this.age = age;
  32.     }
  33.     @JsonAnyGetter // serialize, {"username":"Ada","pwd":"123456","age":26,"key1":"val1","key2":"val2"}
  34.     public Map<String, String> getMap() {
  35.         return map;
  36.     }
  37.     @JsonAnySetter // deserialize, pwd: 123456, age: 26, map: {key1=val1, key2=val2}
  38.     public void setMap(String key, String value) {
  39.         this.map.put(key, value);
  40.     }
  41. }
  42. ---
  43. public static void jsonGetterAndSetter() {
  44.     PersonGetAndSet pgs = new PersonGetAndSet();
  45.     pgs.setUsername("Ada");
  46.     pgs.setAge(26);
  47.     pgs.setPwd("123456");
  48.     pgs.setMap("key1", "val1");
  49.     pgs.setMap("key2", "val2");
  50.     ObjectMapper objectMapper = new ObjectMapper();
  51.     String jsonString = null;
  52.     try {
  53.         jsonString = objectMapper.writeValueAsString(pgs);
  54.         System.out.println(jsonString);
  55.     } catch (Exception e) {
  56.         e.printStackTrace();
  57.     }
  58.     try {
  59.         PersonGetAndSet pgs1 = objectMapper.readValue(jsonString, PersonGetAndSet.class);
  60.         System.out.printf("person -> username: %s, pwd: %s, age: %d, map: %s\n", pgs1.getUsername(), pgs1.getPwd(), pgs1.getAge(), pgs1.getMap());
  61.     } catch (Exception e) {
  62.         e.printStackTrace();
  63.     }
  64. }
  65. ---
复制代码
12.@JsonNaming - 序列化时输出格式

@JsonNaming 加在类上,用以规范序列化时输出的字段键值的形式,主要有以下格式:
  1. package org.example;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.fasterxml.jackson.databind.PropertyNamingStrategy;
  4. import com.fasterxml.jackson.databind.annotation.JsonNaming;
  5. //@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class) // 蛇形体:{"first_name":"Matt","second_name":"Damon"}
  6. //@JsonNaming(value = PropertyNamingStrategy.UpperCamelCaseStrategy.class)  // {"FirstName":"Matt","SecondName":"Damon"}
  7. //@JsonNaming(value = PropertyNamingStrategy.LowerCaseStrategy.class)  // {"firstname":"Matt","secondname":"Damon"}
  8. @JsonNaming(value = PropertyNamingStrategy.LowerDotCaseStrategy.class)  // {"first.name":"Matt","second.name":"Damon"}
  9. public class PersonNaming {
  10.     private String firstName;
  11.     private String secondName;
  12.     public PersonNaming() {
  13.     }
  14.     public PersonNaming(String firstName, String secondName) {
  15.         this.firstName = firstName;
  16.         this.secondName = secondName;
  17.     }
  18.     public String getFirstName() {
  19.         return firstName;
  20.     }
  21.     public void setFirstName(String firstName) {
  22.         this.firstName = firstName;
  23.     }
  24.     public String getSecondName() {
  25.         return secondName;
  26.     }
  27.     public void setSecondName(String secondName) {
  28.         this.secondName = secondName;
  29.     }
  30.     public static void main(String[] args) {
  31.         PersonNaming pn = new PersonNaming();
  32.         pn.setFirstName("Matt");
  33.         pn.setSecondName("Damon");
  34.         ObjectMapper objectMapper = new ObjectMapper();
  35.         try {
  36.             String jsonString = objectMapper.writeValueAsString(pn);
  37.             System.out.println(jsonString);
  38.         } catch (Exception e) {
  39.             e.printStackTrace();
  40.         }
  41.     }
  42. }
复制代码
13.staic 和 transient 字段

如果字段属性中有这两个修饰符,则在序列化处理时忽略相关字段。
参考:

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4