Springboot+FastJson实现解析第三方http接口json数据为实体类(时间格式化转换、字段包含中文)

发布时间 2023-12-08 10:56:41作者: 霸道流氓

场景

若依前后端分离版手把手教你本地搭建环境并运行项目:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662

在上面搭建SpringBoot项目的基础上,并且在项目中引入fastjson、hutool、lombok等所需依赖后。

系统需要对接第三方http接口获取返回的数据,并将json数据解析为实体类进行后续的业务处理。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi

实现

1、使用接口mock工具模拟出一个http的接口,比如使用apifox

 

比如这里接口返回的数据为

{
  "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"
    }
  ]
}

然后进行mock,效果为

 

2、这里发起http客户端请求使用hutool的HttpUtil

 

上面的接口中故意加了一个字段为中文名“地址”,因为第三方系统返回接口数据如此,其它字段均与接口中返回字段对应即可。

然后接口中返回的时间字段为字符串,这里在新建实体类时使用

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

注解即可将时间字符串解析成Date属性字段。

3、新建接口数据响应DTO,用来接受接口响应并判断code字段等

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;
}

这里接口数据返回为data字段,所以新建JSONArray 类型接收。

然后需要将data字段中的数据解析成对象的list。

新建UserDTO用来解析需要的数据

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、新建测试类

调用JSONArray的toJavaList方法将数据解析为java的list对象

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) {

        }
    }
}

运行单元测试,查看解析结果