先导包,略
准备一个Person,用于数据转换
package com.example.demo;
import java.util.Date;
public class Person {
private int age;
private String fullName;
public Person(int age, String fullName) {
super();
this.age = age;
this.fullName= fullName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
常用的转换
package com.example.demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FastJsonTest {
public static void main(String[] args) {
//普通对象转换为Json对象
Person person = new Person(22,"ww");
String string = JSONObject.toJSONString(person);
System.out.println(string);
//字符串转换为Json对象
String person_string = "{\"age\":22,\"fullName\":\"ww\"}";
Person person2 = JSONObject.parseObject(person_string, Person.class);
System.out.println(person.getFullName());
//List转换为Json数组(结果是字符串)
List<Person> personList = new ArrayList<>();
personList.add(new Person(12,"zs"));
personList.add(new Person(22,"zs3"));
String string3 = JSONArray.toJSONString(personList);
System.out.println(string3);
//字符串转成JsonArray对象
String jsonList = "[{\"age\":12,\"fullName\":\"zs\"},{\"age\":22,\"fullName\":\"zs3\"}]";
JSONArray jsonArray = JSON.parseArray(jsonList);
System.out.println(jsonArray);
//后端接收到的Json对象或者JsonArray对象,进行解析,然后返回以String为类型的Json对象或者Json数组
}
}