Spring Boot Json 之 Jackjson

Json is one of the most widely used Internet application usage information exchange format. Spring Boot built in Jackson. Json in the application mainly in the following functions:

  1. Serialization
  2. Deserialization
  3. Field format
  4. Automated verification

Currently used include long assembly Json

  1. Jackson
  2. Gson
  3. FastJson
  4. JSON-B

This chapter focuses on more than 4 functional components in Json 4.

The project github source code download

1 New Spring Boot Maven example projects

Note: IDEA is a development tool for

  1. File> New> Project, select the figure below Spring Initializrand then click [Next] Next
  2. Fill GroupId(package name), Artifact(project name) can be. Click Next
    groupId = com.fishpro
    artifactId json =
  3. The choice depends Spring Web Starterfront tick.
  4. Project name is set spring-boot-study-json.

Test Example 2 coding for

2.1 User entity class

Create two entity classes, user class, user address class, their relationship is a parent-child relationship

User(路径 src/main/java/com/fishpro/json/dto/User.java)

public class User {
    private Integer userId;

    private String username;

    private List<Address> addresses;


    private Calendar created = new GregorianCalendar();


    public User(Integer userId,String username){
        this.userId=userId;
        this.username=username;
    }
    public User(Integer userId,String username,List<Address> addresses){
        this.userId=userId;
        this.username=username;
        this.addresses=addresses;
    }
    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }

    public Calendar getCreated() {
        return created;
    }

    public void setCreated(Calendar created) {
        this.created = created;
    }
}

Address (路径 src/main/java/com/fishpro/json/dto/Address.java)

public class Address {
    private String street;
    private String zipcode;
    private String mobile;

    public Address(String street,String zipcode,String mobile){
        this.street=street;
        this.zipcode=zipcode;
        this.mobile=mobile;
    }
    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

2.2 control layer Code

UserController (路径 src/main/java/com/fishpro/json/controller/UserController.java)

@RequestMapping("/user")
@RestController
public class UserController {

    @GetMapping("/get")
    public User get(){
        List<Address> addressList=new ArrayList<>();
        addressList.add(new Address("江苏省南京市玄武大道1000号","201001","1801989098"));
        addressList.add(new Address("江苏省南京市玄武大道1001号","201001","1811989098"));
        User user = new User(1, "fishpro",addressList);
        return  user;
    }
}

Right-click on the running JsonApplication> Run JsonApplication browser to http: // localhost: 8086 / user / get the system directly returned json format, then Spring Boot default is that the co-yo Jackson to deal with.

{
    "userId": 1,
    "username": "fishpro",
    "addresses": [{
        "street": "江苏省南京市玄武大道1000号",
        "zipcode": "201001",
        "mobile": "1801989098"
    }, {
        "street": "江苏省南京市玄武大道1001号",
        "zipcode": "201001",
        "mobile": "1811989098"
    }],
    "created": "2019-08-13T14:40:50.901+0000"
}

3 Jackson

3.1 dependent on the introduction of Jackson

Without introduction, Spring Boot default to the Jackson to deal with such @RequestBody @ResponseBody

3.2 Configuration Jackson

Such as the 2.2 code samples, using the default Jackson, but the return date formats commonly used formats are not showing people, we will configure his show format from the applicaiton.

server.port = 8086
#jackson
#日期格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#spring.jackson.date-format=yyyy-MM-dd
#格式化输出
spring.jackson.serialization.indent_output=true
#忽略无法转换的对象
spring.jackson.serialization.fail_on_empty_beans=false
#设置空如何序列化
spring.jackson.defaultPropertyInclusion=NON_EMPTY
#允许对象忽略json中不存在的属性
spring.jackson.deserialization.fail_on_unknown_properties=false
#允许出现特殊字符和转义符
spring.jackson.parser.allow_unquoted_control_chars=true
#允许出现单引号
spring.jackson.parser.allow_single_quotes=true

Right-click on the running JsonApplication> Run JsonApplication browser to http: // localhost: 8086 / user / get the system directly returned json format, it is now created to yyy-MM-dd HH: mm: ss show it to us.

{
  "userId" : 1,
  "username" : "fishpro",
  "addresses" : [ {
    "street" : "江苏省南京市玄武大道1000号",
    "zipcode" : "201001",
    "mobile" : "1801989098"
  }, {
    "street" : "江苏省南京市玄武大道1001号",
    "zipcode" : "201001",
    "mobile" : "1811989098"
  } ],
  "created" : "2019-08-13 14:51:48"
}

3.3 Jackson serialization

How to use separate serialization and de-serialization function it

 //测试 Jackson 序列化
        ObjectMapper mapper=new ObjectMapper();//定义一个转化对象
        List<Address> addressList=new ArrayList<>();
        addressList.add(new Address("江苏省南京市玄武大道1000号","201001","1801989098"));
        addressList.add(new Address("江苏省南京市玄武大道1001号","201001","1811989098"));
        User user = new User(1, "fishpro",addressList);
        try {
            String json = mapper.writeValueAsString(user);
            System.out.println(json);

        }catch (Exception e){
            e.printStackTrace();
        }

2.4 Jackson deserialization

 //测试 Jackson 序列化
        ObjectMapper mapper=new ObjectMapper();//定义一个转化对象
        //测试 Jackjson 反序列化
        String json="{\"userId\":2,\"username\":\"程序员\",\"addresses\":[{\"street\":\"江苏省南京市玄武大道1000号\",\"zipcode\":\"201001\",\"mobile\":\"1801989098\"},{\"street\":\"江苏省南京市玄武大道1001号\",\"zipcode\":\"201001\",\"mobile\":\"1811989098\"}],\"created\":1565709784274}";

        try {
            User user2 = mapper.readValue(json, User.class);
            System.out.println(user2);

        }catch (Exception e){
            e.printStackTrace();
        }

2.5 Common Notes

Jackson offers a range of notes, convenient for JSON serialization and de-serialization control, here are some common notes.

@JsonIgnore

@JsonIgnore This annotation is used on the property, the role attribute is ignored when JSON operation.

@JsonFormat

@JsonFormat This annotation is used on the property, the role of type Date converted directly to the desired format, such as @JsonFormat (pattern = "yyyy-MM-dd HH-mm-ss").

For example, a specified time field format alone

    /**更新时间 用户可以点击更新,保存最新更新的时间。**/
    @JsonFormat(pattern="yyyy-MM-dd")
    private Calendar updated = new GregorianCalendar();

@JsonProperty

@JsonProperty This annotation for the attribute, the name of the action attribute is serialized as another name, such as the sequence into trueName attribute name, @ JsonProperty ( "name").

2.6 Issue:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of com.fishpro.json.dto.User (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

Because there is no argument constructor class entity, not shown, all being given, and no solution is to increase the entity class constructor parameters, such as the present example

public User(){}
public Address(){}

reference:

https://www.cnblogs.com/jian-xiao/p/6009435.html?utm_source=itdadao&utm_medium=referral
https://www.cnblogs.com/yuanmo396022993/p/9118308.html

Guess you like

Origin www.cnblogs.com/fishpro/p/spring-boot-study-jackjson.html