Alibaba Fastjson
json string 转 Object
- json string -> JavaBean
1 2 3
Person person = JSON.parseObject(json, Person.class); // 或者 Person person = JSON.parseObject(json, new TypeReference<Person>() {});
- json -> Map
1
Map<String, Person> map = JSON.parseObject(json, new TypeReference<Map<String, Person>>() {});
- json -> List
1 2 3 4 5
List<Person> persons = JSON.parseArray(json, Person.class); // 或者 List<Person> persons = JSON.parseObject(json, new TypeReference<List<Person>>() {}); // 或者(嵌套) List<Map<String, Person>> persons = JSON.parseObject(json, new TypeReference<List<Map<String, Person>>>() {});
对于TypeReference
,由于其构造方法使用 protected 进行修饰,所以在其他包下创建其对象的时候,
要用其实现类的子类:new TypeReference() {} ```java // com.alibaba.fastjson.TypeReference.java 源码 public class TypeReference { private final Type type; public static final Type LIST_STRING = (new TypeReference<List >() { }).getType();
1
2
3
4
5
6
7
8
protected TypeReference() {
Type superClass = this.getClass().getGenericSuperclass();
this.type = ((ParameterizedType)superClass).getActualTypeArguments()[0];
}
public Type getType() {
return this.type;
} } ```
Object 转 json string
- JavaBean -> json string
1
String result = JSON.toJSONString(object);
json Object to JavaObject
1
Person person = JSON.toJavaObject(jsonObject, Person.class);