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);
}
反序列化
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);
}
常用操作
//序列化 str 为 JSONObject
JSONObject jsonObject = JSON.parseObject(str);
//得到要序列化的类型
Type type = new TypeReference<Map<String, Object>>(){}.getType();
//序列化 str 为 Map
Map<String, Object> map = JSON.parseObject(str,type);
map = JSON.parseObject(map.get("Response").toString(),new TypeReference<Map<String, Object>>(){});
//反序列化map 为 string
String s = JSON.toJSONString(map);
//序列化为 JSONArray
JSONArray jsonArray = JSON.parseArray(map.get("TextDetections").toString());
json-lib
//序列化json 为JSONObject
JSONObject jsonObject = JSONObject.fromObject(str);
//JSONObject 转 map
Map<String, Object> map = (Map<String, Object>) jsonObject;
//Map中的value是 JSONObject 对象
JSONObject response = (JSONObject) map.get("Response");
Map<String, String> map1 = (Map<String, String>) response;
//序列化json为 JSONArray
JSONArray jsonArray = JSONArray.fromObject(map1.get("TextDetections"));
Gson
//创建Gson对象
Gson gson = new Gson();
//序列化json 为 LinkedTreeMap 低版本会报错
Map<String, Object> map = gson.fromJson(str, new TypeToken<Map<String, Object>>(){}.getType());
Object response = map.get("Response");
//反序列化为json
String s = gson.toJson(response);
System.out.println(s);
Map<String, Object> map1 = gson.fromJson(s,new TypeToken<Map<String, Object>>(){}.getType());
String string = map1.get("TextDetections").toString();
//序列化为 List类型
Object o = gson.fromJson(string, new TypeToken<List<Map<String, Object>>>() {
}.getType());
System.out.println(o.toString());
参考: