FastJson是阿里开源的JSON库
Maven引入包依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.37</version>
</dependency>
JSONObject
相互转化关系图
- JavaBean
public class 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;}
}
- JSONStr
{"age":20,"name":"xiaoming"}
- JSONObject
{
"age": 20,
"name": "xiaoming",
}
Demo
- JSONObject转JSONStr
public void test() {
JSONObject object = new JSONObject();
object.put("age", 20);
object.put("name", "xiaoming");
String str = JSON.toJSONString(object);
}
- JSONStr转JSONObject
public void test() {
String str = "{\"sex\":\"male\",\"name\":\"xiaoming\",\"age\":20}";
JSONObject object = JSON.parseObject(str);
}
- JSONStr转JavaBean
public void test() {
String str = "{\"sex\":\"male\",\"name\":\"xiaoming\",\"age\":20}";
Person person = JSON.parseObject(str, Person.class);
}
- JavaBean转JSONStr
public void test() {
Person person = new Person(20, "xiaoming");
String str = JSON.toJSONString(person);
}
- JavaBean转JSONObject
public void test() {
Person person = new Person(20, "xiaoming");
JSONObject object = (JSONObject) JSON.toJSON(person);
}
JSONArray
相互转化关系图
- JavaBean
public class 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;}
}
- JSONStr
[{"name":"xiaohua","age":18},{"name":"xiaoming","age":20}]
- JSONArray
[
{
"name": "xiaohua",
"age": 18
},
{
"name": "xiaoming",
"age": 20
}
]
Demo
- JSONArray转JSONStr
public void test() {
JSONObject object1 = new JSONObject();
object1.put("age", 20);
object1.put("name", "xiaoming");
JSONObject object2 = new JSONObject();
object2.put("age", 18);
object2.put("name", "xiaohua");
JSONArray array = new JSONArray();
array.add(object1);
array.add(object2);
String str = JSON.toJSONString(array);
}
- JSONStr转JSONArray
public void test() {
String str = "[{\"name\":\"xiaoming\",\"age\":20},{\"name\":\"xiaohua\",\"age\":18}]";
JSONArray array = JSON.parseArray(str);
}
- JSONStr转JavaBean-List
public void test() {
String str = "[{\"name\":\"xiaoming\",\"age\":20},{\"name\":\"xiaohua\",\"age\":18}]";
List<Person> personList = JSON.parseArray(str, Person.class);
}
- JavaBean-List转JSONStr
public void test() {
Person person1 = new Person(18, "xiaohua");
Person person2 = new Person(20, "xiaoming");
List<Person> personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
String str = JSON.toJSONString(personList);
}
- JavaBean-List转JSONArray
public void test() {
Person person1 = new Person(18, "xiaohua");
Person person2 = new Person(20, "xiaoming");
List<Person> personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
JSONArray array = (JSONArray) JSON.toJSON(personList);
}