1. 首先引入jar包
在pom.xml文件里加入下面依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version> </dependency>
2. 创建一个Person类(方面下面使用)
public class Person implements Comparable<Person> { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(int age, String name) { super(); this.age = age; this.name = name; } }
3. 实现java对象与Json字符串之间的转化
public class Test { public static void main(String[] args) { // 实现java对象与Json字符串之间的转化 // 1. Person对象与json之间的转换 //1.1 将Person对象转成json Person p = new Person(10, "张三"); Object obj = JSONArray.toJSON(p); String json = obj.toString(); System.out.println("将Person对象转成json:" + json); //1.2 将json字符串转成Person对象 Person person = JSONArray.parseObject(json, Person.class); System.out.println("person.getName():" + person.getName()); // 2. 将List<Person>与json之间的转换 //2.1 将List<Person>转成json List<Person> personList = new ArrayList<>(); personList.add(new Person(10, "张三")); personList.add(new Person(10, "李四")); personList.add(new Person(10, "王五")); Object obj2 = JSONArray.toJSON(personList); String json2 = obj2.toString(); System.out.println("将List<Person>转成json:" + json2); // 2.2. 将json字符串转成List<Person>对象 List<Person> list = JSONArray.parseArray(json2, Person.class); System.out.println("list.size():" + list.size()); // 3. 将Map对象与json之间的转换 // 3.1 将Map转成json Map<String, Person> map = new HashMap<>(); map.put("1", new Person(10, "张三")); map.put("2", new Person(10, "李四")); map.put("3", new Person(10, "王五")); Object obj3 = JSONArray.toJSON(map); String json3 = obj3.toString(); System.out.println("将Map<String,Person>转成json:" + json3); // 3.2. 将json转成Map对象 Map<String, Object> map2 = JSONArray.parseObject(json3); Person person2 = JSONArray.parseObject(map2.get("1").toString(), Person.class); System.out.println("person2.getName():" + person2.getName()); } }
运行以上代码,打印结果为:
将Person对象转成json:{"name":"张三","age":10}
person.getName():张三
将List<Person>转成json:[{"name":"张三","age":10},{"name":"李四","age":10},{"name":"王五","age":10}]
list.size():3
将Map<String,Person>转成json:{"1":{"name":"张三","age":10},"2":{"name":"李四","age":10},"3":{"name":"王五","age":10}}
person2.getName():张三