場景
若依前后端分離版手把手教你本地搭建環境并運行項目:
若依前后端分離版手把手教你本地搭建環境并運行項目_前后端分離項目本地運行-CSDN博客
在上面搭建SpringBoot項目的基礎上,并且在項目中引入fastjson、hutool、lombok等所需依賴后。
系統需要對接第三方http接口獲取返回的數據,并將json數據解析為實體類進行后續的業務處理。
注:
博客:
霸道流氓氣質_C#,架構之路,SpringBoot-CSDN博客
實現
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 {@Testpublic 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) {}}
}?
運行單元測試,查看解析結果