maven工程的依赖
com.alibaba fastjson 1.2.45
创建两个实体类 一个是部门类,一个是部门员工类
部门员工类
public class Person { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
部门类
public class Dept { private String deptName; private ListpersonList; public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public List getPersonList() { return personList; } public void setPersonList(List personList) { this.personList = personList; } @Override public String toString() { return "Dept{" + "deptName='" + deptName + '\'' + ", personList=" + personList + '}'; }}
对象转为json字符串格式
JSON.toJSONString(Object object)
@Test public void fun1(){ ListpersonArrayList = new ArrayList (); Person person = new Person(); person.setId(1); person.setName("张三"); person.setAge(18); System.out.println(JSON.toJSONString(person)); personArrayList.add(person); Person person1 = new Person(); person1.setId(2); person1.setName("李四"); person1.setAge(18); personArrayList.add(person1); System.out.println(JSON.toJSONString(person1)); Dept dept = new Dept(); dept.setDeptName("财务部"); dept.setPersonList(personArrayList); String jsonString = JSON.toJSONString(personArrayList); System.out.println(jsonString); }
控制台的打印
JSON字符串转JavaBean
JSON.parseObject(String text,Classclazz)
@Test public void fun2(){ String str1="{\"age\":18,\"id\":1,\"name\":\"张三\"}"; System.out.println(JSON.parseObject(str1,Person.class)); String str2="{\"age\":18,\"id\":2,\"name\":\"李四\"}"; System.out.println(JSON.parseObject(str2,Person.class)); }
控制台打印
JSON字符串数组转List集合
JSON.parseArray(String text, Classclazz)
@Test public void fun3(){ String str="[{\"age\":18,\"id\":1,\"name\":\"张三\"},{\"age\":18,\"id\":2,\"name\":\"李四\"}]"; ListPersonList=JSON.parseArray(str,Person.class); System.out.println(PersonList); }
控制台打印
Map集合转json
JSON.toJSONString(Object object)
@Test public void fun4(){ MappersonMap=new HashMap (); Person person = new Person(); person.setId(1); person.setName("张三"); person.setAge(18); personMap.put("zhangsan",person); Person person1 = new Person(); person1.setId(2); person1.setName("李四"); person1.setAge(18); personMap.put("lisi",person1); String json = JSON.toJSONString(personMap); System.out.println(json); }
控制台打印的信息
MapJson字符串转Map集合
(Map)JSON.parse(Object object)
@Test public void fun5(){ String str="{\"lisi\":{\"age\":18,\"id\":2,\"name\":\"李四\"},\"zhangsan\":{\"age\":18,\"id\":1,\"name\":\"张三\"}}"; Mapmap = (Map)JSONObject.parse(str); System.out.println(map.get("lisi")); System.out.println(map.get("zhangsan")); }
控制台的打印输出