大家好,又见面了,我是你们的朋友全栈君。
场景:
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
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/146311.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...