Fastjson
1.String<->JsonObject(JSONObject对象不存在,只能用类名.静态方法)(parse是反序列化,由字符串变成其他类型,可以理解为将字符串解析为什么什么类型。)
JSONObject jsonObject = JSONObject.parseObject(jsonString);
String jsonString = jsonObject.toJSONString();
2.String<->JsonArray
JSONArray jsonArray = JSONArray.parseArray(jsonString);
String jsonString = jsonArray.toJSONString();//JSONArray.toJSONString(jsonArray);
3.JsonObject->JavaBean(JSONObject对象已存在,可以调用对象方法)
Student student = JSONObject.parseObject(jsonObject.toJSONString(), Student.class);
JSONObject studentJson = JSONObject.parseObject(JSONObject.toJSONString(student));
4.String<->JavaBean
JavaBean javaBean = JSONObject.parseObject(jsonString, JavaBean.class);
String jsonString = JSONObject.toJSONString(javaBean); // 将Java对象序列化为JSON字符串,支持各种各种Java基本类型和JavaBean
5.String<->JavaBeanList
List<Student> studentList = JSONArray.parseArray(josnArrayString, Student.class);
List<Student> students = new ArrayList<Student>();
String jsonString = JSONArray.toJSONString(students);
序列化API
package com.alibaba.fastjson; public abstract class JSON { // 将Java对象序列化为JSON字符串,支持各种各种Java基本类型和JavaBean public static String toJSONString(Object object, SerializerFeature... features); // 将Java对象序列化为JSON字符串,返回JSON字符串的utf-8 bytes public static byte[] toJSONBytes(Object object, SerializerFeature... features); // 将Java对象序列化为JSON字符串,写入到Writer中 public static void writeJSONString(Writer writer, Object object, SerializerFeature... features); // 将Java对象序列化为JSON字符串,按UTF-8编码写入到OutputStream中 public static final int writeJSONString(OutputStream os, // Object object, // SerializerFeature... features); }
反序列化
package com.alibaba.fastjson; public abstract class JSON { // 将JSON字符串反序列化为JavaBean public static <T> T parseObject(String jsonStr, Class<T> clazz, Feature... features); // 将JSON字符串反序列化为JavaBean public static <T> T parseObject(byte[] jsonBytes, // UTF-8格式的JSON字符串 Class<T> clazz, Feature... features); // 将JSON字符串反序列化为泛型类型的JavaBean public static <T> T parseObject(String text, TypeReference<T> type, Feature... features); // 将JSON字符串反序列为JSONObject public static JSONObject parseObject(String text); }