Springboot+FastJson implements parsing third-party http interface json data into entity classes (time format conversion, fields contain Chinese)

Scenes

Ruoyi's front-end and back-end separated version will teach you step by step how to set up the environment and run the project locally:

Ruoyi's front-end and back-end separated version teaches you step-by-step to build the environment and run the project locally_Local running of the front-end and back-end separated projects-CSDN Blog

Based on the SpringBoot project built above, and after introducing the required dependencies such as fastjson, hutool, lombok, etc. into the project.

The system needs to connect to the third-party http interface to obtain the returned data, and parse the json data into entity classes for subsequent business processing.

Note:

Blog:
Domineering hooligan temperament_C#, architecture road, SpringBoot-CSDN blog

accomplish

1. Use the interface mock tool to simulate an http interface, such as using apifox

For example, the data returned by the interface here is

{
  "code": "200",
  "data": [
    {
      "id": "38",
      "name": "成生认两",
      "time_cur": "1984-01-29 17:55:39",
      "地址": "mollit"
    },
    {
      "id": "61",
      "name": "质立红几算往值",
      "time_cur": "2013-01-27 06:38:34",
      "地址": "est enim"
    },
    {
      "id": "53",
      "name": "办单正决风放",
      "time_cur": "2008-10-18 14:00:37",
      "地址": "ex commodo nisi"
    },
    {
      "id": "54",
      "name": "角件二心任眼",
      "time_cur": "1978-11-14 10:13:04",
      "地址": "nisi exercitation quis voluptate"
    }
  ]
}

Then mock, the effect is:

2. Initiate http client request here using hutool’s HttpUtil

The above interface deliberately adds a field with the Chinese name "address" because the third-party system returns the interface data like this, and other fields can correspond to the fields returned in the interface.

Then the time field returned in the interface is a string, which is used when creating a new entity class.

  @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss")

The annotation can parse the time string into a Date attribute field.

3. Create a new interface data response DTO to accept the interface response and determine the code field, etc.

import com.alibaba.fastjson.JSONArray;
import lombok.Data;
import java.io.Serializable;

@Data
public class UserResDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 响应编码
     */
    private Integer code;
    /**
     * 数据
     */
    private JSONArray data;
}

The interface data here is returned as the data field, so the new JSONArray type is received.

Then you need to parse the data in the data field into a list of objects.

Create a new UserDTO to parse the required data

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;

@Data
public class UserDTO {
    private String id;
    private String name;
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss")
    private Date time_cur;
    private String 地址;
    private String remark;
}

4. Create a new test class

Call the toJavaList method of JSONArray to parse the data into a Java list object


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.test.dto.UserDTO;
import com.ruoyi.system.domain.test.dto.UserResDTO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RuoYiApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FastJsonTest {

    @Test
    public void getUserData() {
        String body = "";
        try {
            body = HttpRequest
                    .get("http://127.0.0.1:4523/m1/2858210-0-default/testFastJson")
                    .timeout(20000)
                    .execute()
                    .body();
            UserResDTO userResDTO = JSON.parseObject(body, UserResDTO.class);
            if (userResDTO.getCode() != null && 200!=userResDTO.getCode()) {
                //错误处理
            }else {
                JSONArray data = userResDTO.getData();
                if (StringUtils.isEmpty(data)) {
                    return;
                }
                List<UserDTO> userDTOS = data.toJavaList(UserDTO.class);
                System.out.println(userDTOS.toString());
            }
        } catch (Exception e) {

        }
    }
}

Run the unit test and view the parsing results

Guess you like

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/134872936