使用了阿里巴巴的 fastjson 首先引入依赖
com.alibaba fastjson 2.0.32
示例如下
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;@Log4j2public class JsonToListTest { public static void main(String[] args) { List studentList = new ArrayList<>(); Student student1 = new Student("张三", 23, "女", "山东省烟台市芝罘区环海路2号"); Student student2 = new Student("李四", 19, "男", "安徽省六安市霍邱县安徽霍邱经济开发区G35济广高速"); studentList.add(student1); studentList.add(student2); Map 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 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