首页 > 编程知识 正文

json字符串转listmap集合,list对象转json字符串

时间:2023-05-05 03:43:40 阅读:241511 作者:2172

场景:
       JSON字符串转List集合与List集合转JSON字符串
       使用的jar包是fastjson-1.2.41.jar 
1.JSON字符串转List集合操作

public static <T> List<T> parseArray(String text, Class<T> clazz) { try { return JSON.parseArray(text, clazz); } catch (Exception e) { } return Collections.emptyList();}

 2.List集合转JSON字符串操作

public static String toJSONString2(Object obj) { JSONArray jsonObj = (JSONArray) JSONArray.toJSON(obj); return jsonObj.toJSONString();}

3.测试demo的main函数

public static void main(String []args){ System.out.println("测试开始"); //对象一 DemoModel model = new DemoModel(); model.setId(12345678); model.setType("01"); model.setZ(1111.2222); model.setZ1(3333.4444); model.setZ2(5555.6666); model.setZ3(7777.8888); //对象二 DemoModel model1 = new DemoModel(); model1.setId(87654321); model1.setType("02"); model1.setZ(2222.1111); model1.setZ1(4444.3333); model1.setZ2(6666.5555); model1.setZ3(8888.7777); //新建List List list = new ArrayList(); list.add(model); list.add(model1); //List集合转JSON字符串 String result = toJSONString2(list); System.out.println(result); //JSON字符串转List集合 List list2 = parseArray(result,DemoModel.class); for(int i=0;i<list2.size();i++){ DemoModel modelTemp = (DemoModel) list2.get(i); System.out.println("取值 z1=" + modelTemp.getZ1()); } System.out.println("测试结束");}

4.实体对象DemoModel.java

public class DemoModel implements Serializable{ private static final long serialVersionUID = 6428876123605652053L; private long id; private String type; private double z; private double z1; private double z2; private double z3; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } public double getZ1() { return z1; } public void setZ1(double z1) { this.z1 = z1; } public double getZ2() { return z2; } public void setZ2(double z2) { this.z2 = z2; } public double getZ3() { return z3; } public void setZ3(double z3) { this.z3 = z3; }}

以上,TKS

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。