一,简介
由阿里巴巴开发,是一种高性能的JSON解析工具
①快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson)
②强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
③零依赖(没有依赖其它任何类库除了JDK)
解析对象:
JSON.parseObject(String str, Class<T>);
import com.alibaba.fastjson.JSON;
public class FastJsonDemo01 {
public static void main(String[] args) {
String jsonStr = "{'name':'mixm','age':21,'gender':'男','hobby':['football','basketball']}";
Person p = JSON.parseObject(jsonStr, Person.class);
System.out.println(p);
}
}
解析数组:
JSON.parseArray(String str, Class<T>)
import java.util.List;
import com.alibaba.fastjson.JSON;
public class FastJsonDemo02 {
public static void main(String[] args) {
String jsonStr = "[{'name':'mixm','age':21,'gender':'男','hobby':['football','basketball']},{'name':'mixm2','age':22,'gender':'男','hobby':['football','basketball']}]";
List<Person> p = JSON.parseArray(jsonStr, Person.class);
for (Person person : p) {
System.out.println(person);
}
}
}
生成JSON字符串:JSON.toJSON(Object obj);
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.mixm.json.ch05.Person;
public class FastJsonDemo03 {
public static void main(String[] args) {
List<String> hobby = new ArrayList<>();
hobby.add("football");
hobby.add("basketball");
Person p1 = new Person("mixm", 21, "男", hobby);
p1.setHobby(hobby);
//对象
Object obj = JSON.toJSON(p1);
System.out.println(obj);
//数组
List<Person> persons = new ArrayList<>();
persons.add(p1);
Person p2 = new Person("marry", 23, "女", hobby);
persons.add(p2);
obj = JSON.toJSON(persons);
System.out.println(obj);
}
}