Jackson

first you need to add dependence:
gradle:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.1'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.1'

原生Jackson的使用示例:

/**
 * 原生Jackson的使用示例
 */
public class JacksonUsageDemo {

  public static void main(String[] args) throws JsonProcessingException {
    Address address1 = new Address("北京", "王府井12号", true);
    Address address2 = new Address("成都", "天府大道55号", false);
    Person person = new Person("张三", 18, Gender.MALE, Arrays.asList(address1, address2));

    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(person);
    System.out.println(json);

    Person result = objectMapper.readValue(json, Person.class);
    System.out.println(result);
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class Person {

    private String name;
    private Integer age;
    private Gender gender;
    private List<Address> addressList;
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class Address {

    private String city;
    private String detail;
    private Boolean isPrimary;
  }

  private enum Gender {
    MALE, FEMALE;
  }
}

if JSON and JavaBean are not same

场景一:JSON比JavaBean多字段,在反序列化时忽略未知字段

使用@JsonIgnoreProperties:可以忽略指定字段,也可以忽略本类所有未知字段

  • @JsonIgnoreProperties(value = “year”):ignore the value of json
  • @JsonIgnoreProperties(ignoreUnknown = true):ignore every unknown value of JSON
  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  @JsonIgnoreProperties(value = "year")
//  @JsonIgnoreProperties(ignoreUnknown = true)
  private static class Car {

    private String color;
    private String type;
  }

场景二:需要的JSON比JavaBean少字段,在序列化时忽略多余字段

  • 用@JsonIgnore在字段级别忽略
  • 用@JsonIgnoreType在类级别忽略
@RestController
public class FieldsLessController {

  @GetMapping("/teachers/{id}")
  public Teacher getStudentById(@PathVariable("id") String id) {
    return new Teacher(id, "刘老师", Gender.FEMALE);
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class Teacher {

    private String id;
    private String name;

    @JsonIgnore
    private Gender gender;
  }

  //  @JsonIgnoreType
  private enum Gender {
    MALE, FEMALE;
  }
}

场景三:字段名不一致,在序列化和反序列化时改变字段名

  • 使用@JsonProperty
@RestController
public class FieldsNameMismatchController {

  @GetMapping("/articles/{id}")
  public Article getStudentById(@PathVariable("id") String id) {
    return new Article(id, "论持久战");
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class Article {

    @JsonProperty("articleId")
    private String id;
    @JsonProperty("articleTitle")
    private String title;
  }
}

json将会返回articleI&&articleTitle

场景四:结构不一致,在序列化时将对象拍平

  • 使用@JsonUnwrapped

拍平后:
{
“id”: “1”,
“firstName”: “John”,
“lastName”: “Doe”
}

@RestController
@Slf4j
public class StructureMismatchController {

  @PostMapping("/employees")
  public void createEmployee(@RequestBody Employee employee) {
    log.info("create employee: {}", employee);
  }

  @GetMapping("/employees/{id}")
  public Employee getStudentById(@PathVariable("id") String id) {
    return new Employee(id, new Name("John", "Doe"));
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class Employee {

    private String id;
    @JsonUnwrapped
    private Name name;
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class Name {

    private String firstName;
    private String lastName;
  }
}

场景五:JSON中的枚举是数字形式,在序列化时使用枚举的序数值

  • 使用@JsonValue
@RestController
public class EnumOrdinalController {

  @GetMapping("/users/v1/{id}")
  public User getUserById(@PathVariable String id) {
    return new User(id, "小红", Gender.FEMALE);
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class User {

    private String id;
    private String name;
    private Gender gender;
  }

  private static enum Gender {
    MALE, FEMALE;

    @JsonValue
    public int getOrdinal() {
      return ordinal();
    }
  }
}

场景六:JSON中的时间是特定格式,在序列化时指定时间格式

  • 使用@JsonFormat
@RestController
public class TimeFormatController {

  @GetMapping("/events/{id}")
  public Event getEvent(@PathVariable("id") String id) {
    return new Event(id, "pay", new Date());
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class Event {

    private String id;

    private String name;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date time;
  }
} 

使用自定义序列化器,枚举序列化成数字

@JsonSerialize(using = GenderSerializer.class)

@RestController
public class CustomSerializationController {

  @GetMapping("/users/v2/{id}")
  public User getUserById(@PathVariable String id) {
    return new User(id, "小红", Gender.FEMALE);
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  private static class User {

    private String id;
    private String name;
    @JsonSerialize(using = GenderSerializer.class)
    private Gender gender;
  }

  private static enum Gender {
    MALE, FEMALE;
  }

  private static class GenderSerializer extends StdSerializer<Gender> {

    protected GenderSerializer() {
      super(Gender.class);
    }

    @Override
    public void serialize(Gender value, JsonGenerator gen, SerializerProvider provider)
        throws IOException {
      gen.writeNumber(value.ordinal());
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值