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());