json和對象互轉
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class Json {
public static void main(String[] args) {
//對象轉換爲json格式
Student student = new Student("張三","男");
String s = JSON.toJSONString(student);
System.out.println(s);
//列表轉換爲JSON
List<Student> students = new ArrayList<>();
students.add(student);
students.add(new Student("李四","男"));
String s1 = JSON.toJSONString(students);
System.out.println(s1);
//將JSON字符串轉換爲對象
String jsonStr = "{\"name\":\"張三\",\"sex\":\"男\"}";
Student student1 = JSON.parseObject(jsonStr, Student.class);
System.out.println(student1);
}
}
運行結果
Student student = new Student("張三","男");
//給前端返回數據
//一個空的json對象
JSONObject jsonObject = new JSONObject();
//添加數據
jsonObject.put("status",200);
jsonObject.put("data",student);
//轉換爲json字符串
String s2 = JSON.toJSONString(jsonObject);
System.out.println(s2);