使用了阿里巴巴的 fastjson 首先引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.32</version>
</dependency>
示例如下文章来源:https://www.toymoban.com/news/detail-617941.html
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);
}
}
输出结果:文章来源地址https://www.toymoban.com/news/detail-617941.html
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
到了这里,关于Java List对象集合转Json & Json转List对象集合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!