Conversion between java and json: a detailed analysis of the case using the call method writeValueAsString()

1. Call the method writeValueAsString()

1.1 Create an entity class object

package com.fy.test;

public class Student {
    
    

    private int id;
    private String name;
    private boolean sex;

    public Student(int id, String name, boolean sex) {
    
    
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public Student() {
    
    

    }

    public Student(int i, String zhu) {
    
    

    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public boolean isSex() {
    
    
        return sex;
    }

    public void setSex(boolean sex) {
    
    
        this.sex = sex;
    }
}

1.2 Java objects converted into json data

package com.fy.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

/**
 * json 与 java 的转换
 * 调用方法:writeValueAsString()
 */
public class TestJackson {
    
    
    @Test
    public void f() throws Exception {
    
    
        //创建Jackson的核心对象ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //创建要转换成json数据的java对象
        Student student = new Student(12,"zhu",true);
        //调用writeValueAsString,将指定的对象转换成json
        String json = mapper.writeValueAsString(student);
        System.out.println(json);
    }
}

operation result

Guess you like

Origin blog.csdn.net/zhu_fangyuan/article/details/108719641