使用了阿里巴巴的 fastjson 首先引入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.32</version> </dependency>
import com.alibaba.fastjson.JSONObject; import com.example.springbootdemo.domain.dto.Student; import lombok.extern.log4j.Log4j2; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author Let's go Lakers * @Date 2023/5/30 **/ @Log4j2 public class JsonToListTest { public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); Student student1 = new Student("张三", 23, "女", "山东省烟台市芝罘区环海路2号"); Student student2 = new Student("李四", 19, "男", "安徽省六安市霍邱县安徽霍邱经济开发区G35济广高速"); studentList.add(student1); studentList.add(student2); Map<String, Object> param = new HashMap<>(); param.put("studentList", studentList); // 把List对象集合作为json格式推给第三方接口 log.info("入参:" + JSONObject.toJSONString(param)); // 调用三方接口 //HttpUtil.post("/urlTest", JSONObject.toJSONString(param), 5); // 三方接收并转为list对象集合 String result = JSONObject.toJSONString(param); log.info("三方接收:" + result); JSONObject studentJson = JSONObject.parseObject(result); // 转成list对象集合 List<Student> studentLists = JSONObject.parseArray(studentJson.get("studentList").toString(), Student.class); log.info("studentList: " + studentList); log.info("studentLists: " + studentLists); } }
09:47:06.833 [main] INFO com.example.springbootdemo.Test.JsonToListTest - 入参:{"studentList":[{"address":"山东省烟台市芝罘区环海路2号","age":23,"name":"张三","sex":"女"},{"address":"安徽省六安市霍邱县安徽霍邱经济开发区G35济广高速","age":19,"name":"李四","sex":"男"}]} 09:47:06.836 [main] INFO com.example.springbootdemo.Test.JsonToListTest - 三方接收:{"studentList":[{"address":"山东省烟台市芝罘区环海路2号","age":23,"name":"张三","sex":"女"},{"address":"安徽省六安市霍邱县安徽霍邱经济开发区G35济广高速","age":19,"name":"李四","sex":"男"}]} 09:47:06.855 [main] INFO com.example.springbootdemo.Test.JsonToListTest - studentList: [Student(name=张三, age=23, sex=女, address=山东省烟台市芝罘区环海路2号), Student(name=李四, age=19, sex=男, address=安徽省六安市霍邱县安徽霍邱经济开发区G35济广高速)] 09:47:06.855 [main] INFO com.example.springbootdemo.Test.JsonToListTest - studentLists: [Student(name=张三, age=23, sex=女, address=山东省烟台市芝罘区环海路2号), Student(name=李四, age=19, sex=男, address=安徽省六安市霍邱县安徽霍邱经济开发区G35济广高速)] Process finished with exit code 0
来源:https://blog.csdn.net/zxc_wzhzjqeds/article/details/130941993