简介
fastjson 是一个性能很好的 Java 语言实现的 JSON 解析器和生成器,来自阿里巴巴的工程师开发。
主要特点:
- 快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson)
- 强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
- 零依赖(没有依赖其它任何类库除了JDK)
代码体会
java
//用户对象转为Json串
Person person1 = new Person("redgo",20);
String json_person1 = JSON.toJSONString(person1); //{"age":20,"name":"redgo"}
Person person2 = new Person("bluego",22);
String json_person2 = JSON.toJSONString(person2); //{"age":22,"name":"redgo"}
//List对象转为Json串
List<Person> list = new ArrayList<Person>();
list.add(person1);
list.add(person2);
String json_list = JSON.toJSONString(list); //[{"age":20,"name":"redgo"},{"age":22,"name":"bluego"}]
//JSON串转为用户对象
person1 =JSON.parSEObject(json_person1,Person.class);
//JSON串转为List对象
list = JSON.parseArray(json_list,Person.class);
//用户组对象(包含List集合)转为Json串
PersonGroup personGroup = new PersonGroup("亲戚",list);
String json_personGroup = JSON.toJSONString(personGroup);
//{"name":"亲戚","persons":[{"age":20,"name":"bluego"}]}
//JSON串转为用户组对象(包含List集合)
personGroup =JSON.parSEObject(json_personGroup,PersonGroup.class);
Person 类
java
public class Person {
private String name;
private int age;
public Person(){}
public Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ",age=" + age + "]";
}
}
PersonGroup类
java
public class PersonGroup {
private String name;
private List<Person> persons = new ArrayList<Person>();
public PersonGroup(){};
public PersonGroup(String name,List<Person> persons){
this.name = name;
this.persons = persons;
};
@Override
public String toString() {
return "PersonGroup [name=" + name + ",persons=" + persons + "]";
}
}