这里用到的是alibaba的fastjson库。
在pom.xml文件添加如下内容:
com.alibaba
fastjson
1.2.47
实体类:
public class emp implements Serializable{
private String id;
private String name;
private String salary;
private String age;
}
构造器和getter和setter就不贴了。
import com.alibaba.fastjson.JSON;
List
emp e=new emp();
e.setId("03");
e.setName("yangguo");
e.setSalary("10000");
e.setAge("18");
emp e1=new emp();
e1.setId("04");
e1.setName("xiaolongnv");
e1.setSalary("9000");
e1.setAge("17");
List list =new ArrayList<>();
list.add(e);
list.add(e1);
String json1=JSON.toJSONString(list);
System.out.println(json1);
结果:
[{
"age": "38",
"id": "03",
"name": "yangguo",
"salary": "10000"
}, {
"age": "17",
"id": "04",
"name": "xiaolongnv",
"salary": "9000"
}]
Map
Map map=new HashMap();
map.put("id","01");
map.put("name","guojing");
map.put("salary","8000");
map.put("age","18");
Map map1=new HashMap();
map1.put("id","02");
map1.put("name","huangrong");
map1.put("salary","7000");
map1.put("age","17");
String json=JSON.toJSONString(map);
String json1=JSON.toJSONString(map1);
System.out.println(json);
System.out.println(json1);
结果:
{
"id": "01",
"age": "18",
"name": "guojing",
"salary": "8000"
}
{
"id": "02",
"age": "17",
"name": "huangrong",
"salary": "7000"
}
List
List
结果:
[{
"id": "01",
"age": "18",
"name": "guojing",
"salary": "8000"
}, {
"id": "02",
"age": "17",
"name": "huangrong",
"salary": "7000"
}]