Java List对象集合转Json & Json转List对象集合
短信预约 -IT技能 免费直播动态提醒
使用了阿里巴巴的 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
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341