Use jackson to parse json data in detail

Java manipulation of json data

Introduction to json

concept

  JSON: JavaScript Object Notations, that is, the object notation of javaScript, is a subset of the grammar of javaScript, which is equivalent to an object in javaScript. Although json originated from javaScript, many languages ​​support the analysis and generation of json data format, which is a text data format . The official MIME type is application/json .
  

Application scenario

  1. Commonly used in web applications developed using javaScript, java, node.js.
  2. Because of the text data stored in json, it is also used in some NoSql-type document-based databases, such as MongoDB.

Compared with XML, JSON is lighter, easier to parse, and data transmission is faster.
  
Grammar format

   As mentioned earlier, json is a subset of javaScript, and its manifestation is a java curly brace data object. At the same time, the json data format has strict grammatical requirements, and if there is a problem, the analysis will fail. The grammar rules are as follows:

The data in json exists in the form of key-value pairs. The following requirements are imposed on key-value pairs:

  1. Both the key and the value need to be enclosed in double quotation marks, and the key must be a string, and the value can be various javascript types, or another json object
  2. Different key-value pairs should be separated by commas, but be careful not to use commas in the last key-value pair, otherwise an error will be reported
  3. A json object needs to be wrapped in curly braces
  4. The value of the array needs to be enclosed in square brackets

Type of json value:

  1. String
  2. Number
  3. Object Json
  4. Array
  5. Boolean
  6. null

It cannot be undefined, function, or date type in javaScript.

For example

person = {
    
    
    "name":"zhangsan",
    "age":21,
    "girlFriend":{
    
    "name":"lisi", "age":20},
    "hobbies":["跑步", "篮球", "打机"],
    "single":false
}

  Sometimes the data in json format that we request from the network is not so neat. At this time, you can use the json online parsing tool , and copy the json string to view the specific outline of the data.

Note that annotations are not allowed in json data. If you want to annotate, you need to perform some other operations. You can check the specific reasons online.
  
json string

  That is, the outer curly braces of the json object are wrapped in double quotation marks. During the data transmission process, the data is often converted into a json string, and then parsed into a json object. E.g

String person = "{
    
    
    "name":"zhangsan",
    "age":21,
    "girlFriend":{
    
    "name":"lisi", "age":20},
    "hobbies":["跑步", "篮球", "打机"],
    "single":false
}";

Read data in javaScript

  1. json object. key name – person.name = "zhangsan"
  2. json object["key name"] – person["age"] = 21
  3. json object. Array object [index] – person.hobbies[2] = "Hit machine"
  4. You can use the above for nested use – person.girlFriend.name = "lisi"

  

java manipulate json data

   The json data format can be used in the front and back data transmission of web applications, for example, the front end sends ajax request data. When java is used as the back-end development language, corresponding analysis is needed to generate json data tool class. The following introduces a concise and fast json parsing tool class: jackson .

   jackson by deserialization (usually a custom class instances), may be transferred json java object passed into a target tip java object serialization to json object, passing to the front page is received.

  1. Serialization: the process of converting java objects into byte stream data,
  2. Deserialization: The process of converting byte stream data into java objects,

Note: Although json is a text data format, it still needs to be converted into byte stream data for transmission during network transmission.

The following is the use of jackson

2.1 Import jar packages or dependencies

Import the jar package

There are three jars related to jackson, namely:

  1. jackson-annotations.jar-download link: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations
  2. jackson-core.jar-download link: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
  3. jackson-databind-download link: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

Enter the corresponding address, click on any version number and then click "view all" (Chinese webpage) or "view all" (English webpage), then the interface is as follows:

jackson jar package

The download of the other two jar packages is the same.

Import in the maven project

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.11.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.11.2</version>
</dependency>

  Since the jackson-databind dependency is imported, the other two dependencies will also be imported at the same time, so it is OK to import only the jackson-databind dependency in the project import.

2.2 Convert java object to json string

  The class used to sequence and deserialize json data in jackson is ObjectMapper (object mapping) ; in the package: com.fasterxml.jackson.databind. The following example illustrates the use of ObjectMapper objects: Assume that the domain object of Person has been created

1. Convert the java object into a json format string

public void test() {
    
    
    Person p = new Person();
    p.setName("张三");
    p.setAge(21);
   	
    ObjectMapper mapper = new ObjectMapper();		//直接创建该对象即可调用相关方法
    String json = mapper.writeValueAsString(p);		//即可将p对象转化为json格式的字符串 -- "{"name":"张三", "age":21}"
}

  writeValueAsString(Object obj): A domain object can be converted into a corresponding json string. If there is an attribute in the domain without a value, it will be replaced by null. Very commonly used!

  Both List collection and Map object can use this method. List collection transforms the format of an array nested object, and the format transformed by Map object is the same as the format transformed by using domian object.

2. Convert the java object into a json string and write it to the target source

  1. writeValue(File file, Objcet obj); – Write the content of the obj object to the File file
  2. writeValue(Writer writer, Object obj); – write the obj object to the Writer character stream object
  3. writeValue(OutputStream output, Object obj); – write the obj object to the OutputStream byte stream object
public void test() {
    
    
    Person p = new Person();
    p.setName("张三");
    p.setAge(21);
   	
    ObjectMapper mapper = new ObjectMapper();			//直接创建该对象即可调用相关方法
	mapper.writeValue(new File("D://test.txt"), p);		//将p对象写入File对象
    mapper.writeValue(new FileWrite("D://test1.txt"), p);
    mapper.writeValue(new FileOutputStream(new File("D://test2.txt")), p);
}

2.3 Jackson related notes

  • As mentioned above, when converting a java object into an ObjectMapper object, if the related property has no value, it will be converted to null. If we don't need the related property, we can add the following annotation to the statement defining the property:

@JsonIgnore

E.g:

@JsonIgnore

private int money;

In this way, when it is converted into a json string object, the attribute conversion will not be discussed.

  • For the conversion of time attributes, the following annotations can be used

    @JsonFormat(pattern = “yyyy-MM-dd”)

    private Date birthday;

The time format displayed in this way is: 2020-09-30, if the above annotation is not used, the timestamp of the corresponding time will be displayed.

2.4 Convert json to java object

It is also possible to convert a json string into a java domain object through the ObjectMapper method, but it is not used much. The specific usage is as follows:

public void test() {
    
    
    ObjectMapper mapper = new ObjectMapper();		//直接创建该对象即可调用相关方法
    String json = "{"name":"张三", "age":21}";
    Person person = mapper.readValue(json, Person.class);		//可将json字符串转化为Person对象 
}

This method is not so commonly used.

  

Examples of front-end data interaction

Simulate user login, determine whether the user name and password entered by the user match, whether the verification code is correct, and if the verification code is correct, the corresponding prompt information will be returned. The ResultInfo object is a domian object that is used to save the corresponding error information.

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        Map<String, String[]> map = request.getParameterMap();
        ResultInfo info = new ResultInfo();
        ObjectMapper mapper = new ObjectMapper();		//创建ObjectMapper对象
		
		//获取验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");
        String checkcode = request.getParameter("check");
        
        if (!checkcode.equalsIgnoreCase(checkcode_server)) {
    
    
            info.setFlag(false);
            info.setErrorMsg("验证码错误");
            String json = mapper.writeValueAsString(info);	//将对象转化成json字符串
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);	//将对象写会前端
            return ;
        } else {
    
    
            User user = new User();
            try {
    
    
                BeanUtils.populate(user, map);
                //将用户信息保留在session中
                session.setAttribute("user", user);
            } catch (IllegalAccessException e) {
    
    
                e.printStackTrace();
            } catch (InvocationTargetException e) {
    
    
                e.printStackTrace();
            }
            UserService service = new UserServiceImpl();
            boolean status = service.login(user);
            if (status) {
    
    
                if (!service.hasCertification(user)) {
    
    
                    info.setFlag(false);
                    info.setErrorMsg("邮箱还没有认证,请查看您的邮箱进行认证!");
                } else {
    
    
                    info.setFlag(true);
                }
            } else {
    
    
                info.setFlag(false);
                info.setErrorMsg("账号或密码错误");
            }
            String json = mapper.writeValueAsString(info);	//将对象转化成json字符串
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);	//将对象写会前端
        }

    }

ResultInfo class:

package cn.itcast.travel.domain;

import java.io.Serializable;
import java.util.Objects;

/**
 * 1.用于封装后端返回前端数据对象
 * 2.同时判断返回的数据是否有误
 * 3.记录其发生异常的信息 -- 注意这里是用来展示到前台上的错误信息
 */
public class ResultInfo implements Serializable {
    
    
    /**
     * true: 后端返回结果正常
     * false:后端返回结果错误
     */
    private boolean flag;
    /**
     * 后端返回结果的数据对象
     */
    private Object data;
    /**
     * 发生异常的错误信息
     */
    private String errorMsg;

    public ResultInfo() {
    
    }

    /**
     * 带参构造
     * @param flag
     */
    public ResultInfo(boolean flag) {
    
    
        this.flag = flag;
    }
    /**
     * 有参构造方法
     * @param flag
     * @param errorMsg
     */
    public ResultInfo(boolean flag, String errorMsg) {
    
    
        this.flag = flag;
        this.errorMsg = errorMsg;
    }
    /**
     * 有参构造方法
     * @param flag
     * @param data
     * @param errorMsg
     */
    public ResultInfo(boolean flag, Object data, String errorMsg) {
    
    
        this.flag = flag;
        this.data = data;
        this.errorMsg = errorMsg;
    }

    public boolean isFlag() {
    
    
        return flag;
    }

    public void setFlag(boolean flag) {
    
    
        this.flag = flag;
    }

    public Object getData() {
    
    
        return data;
    }

    public void setData(Object data) {
    
    
        this.data = data;
    }

    public String getErrorMsg() {
    
    
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
    
    
        this.errorMsg = errorMsg;
    }
}

Guess you like

Origin blog.csdn.net/weixin_44184990/article/details/108882989