fastjson
轉JSON
示例轉一個對象和一個數組
Student student = new Student(1, "張三");
Student student1 = new Student(2, "李四");
List<Student> list = new ArrayList<>();
list.add(student);
list.add(student1);
// 開轉
String jsonString = JSON.toJSONString(student);
String jsonArrayString = JSON.toJSONString(list);
System.out.println(jsonString);
System.out.println(jsonArrayString);
解析JSON
JSONObject jsonObject = JSON.parseObject(jsonString);
// Student類需要有默認的構造函數
Student jsonStringToStudent = JSON.parseObject(jsonString, Student.class);
// 想轉具體的java類型傳個.class就完事了
JSONArray jsonArray = JSON.parseArray(jsonArrayString);
List<Student> students = JSON.parseArray(jsonArrayString, Student.class);
GSON
轉JSON
Gson gson = new Gson();
String palletIds = "[1,2,3,4,5]";
List<Integer> list = gson.fromJson(palletIds, new TypeToken<List<Integer>>() {}.getType());
System.out.println(list.toString());
String json = gson.toJson(list);
// [1,2,3,4,5]
System.out.println(json);
解析JSON
Gson gson = new Gson();
String palletIds = "[1,2,3,4,5]";
List<Integer> list = gson.fromJson(palletIds, new TypeToken<List<Integer>>() {}.getType());
// [1, 2, 3, 4, 5]
System.out.println(list.toString());