类的映射

  • Data class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
  package cn.matgene.jack;

  import lombok.AllArgsConstructor;
  import lombok.Data;
  import lombok.NoArgsConstructor;
  import lombok.Value;

  @Data
  @AllArgsConstructor
  @NoArgsConstructor
  public class Person {
private String name;
private long id;

  }
  • Test and convert class to json

    • 注意:

      • 需要在方法中添加 throws
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
  package cn.matgene.jack;

  import com.fasterxml.jackson.core.JsonProcessingException;
  import com.fasterxml.jackson.databind.ObjectMapper;

  public class TestJson {
public static void main(String[] args) throws JsonProcessingException {
   ObjectMapper mapper = new ObjectMapper();

   Person lucy = new Person("Lucy", 1);
   String str = mapper.writeValueAsString(lucy);
   System.out.println(str);

}
  }

注解 annotations

属性更名

@JsonProperty

  • 作用于字段
  • eg: @JsonProperty(value='lucy')

    • 改名成 'lucy'
  • 属性 —> json 的 key
  • 属性

    • value: 指定更改名称
    • index: 指定字段的 json key 顺序

忽略特定字段

@JsonIgnore

忽略一个字段

  • 作用于字段

@JsonIgnoreProperties

  • 类注解
  • eg:

    1
    
    @JsonIgnoreProperties({"prop1", "prop2"})
  • 注解的属性

    • ignoreUnknow = true

@JsonIgnoreType

  • 类注解

指定字段顺序

@JsonPropertyOrder

根属性名称

相当于指定类的打印名称

  • json 根属性名称

@JsonRootName

集合的映射

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
  ObjectMapper mapper = new ObjectMapper();

  Map<String, Object> map = new HashMap<>();
  map.put("age", 25);
  map.put("name", "yitian");
  map.put("interests", new String[]{"pc games", "music"});

  String text = mapper.writeValueAsString(map);
  System.out.println(text);

  Map<String, Object> map2 = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
  });
  System.out.println(map2);

  JsonNode root = mapper.readTree(text);
  String name = root.get("name").asText();
  int age = root.get("age").asInt();

  System.out.println("name:" + name + " age:" + age);