fastJson相关文档和源码
简单认识fastJson fastJson是一个 Java 库,可以 将Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象,同时它还可以操作任何 Java 对象,即使是一些 预先存在的没有源码的对象 。
有时间可以
1.Fastjson常用的使用方法
1.1.jsonString convert to javabean
import com.alibaba.fastjson.*; //用法一 :jsonString 转换JSONObject JSONObject jsonObj = JSON.parseObject(jsonStr); //用法二 :JSONString转换成bean/Map Model model = JSON.parseObject(jsonStr, Model.class); //用法三 :JSONString转换自定义泛型 Type type = new TypeReference<List<Model>>() { }.getType(); List<Model> list = JSON.parseObject(jsonStr, type);
1.2.javabean to jsonString
import com.alibaba.fastjson.JSON; //用法一 : 对象转换成jsonString Model model = ...; String jsonStr = JSON.toJSONString(model); //用法二 : 对象转换成jsonString格式的byte数组 byte[] jsonBytes = JSON.toJSONBytes(model); //用法三 : 对象转换成jsonString并将jsonString保存到OutputStream 或Writer OutputStream os; JSON.writeJSONString(os, model); Writer writer = ...; JSON.writeJSONString(writer, model);
2.Fastjson具体使用
2.1.Bean对象与jsonString的相互转换
import com.alibaba.fastjson.JSON; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; public class Test1 { public static void main(String[] args) { Map<String,Object> jsonMap = new HashMap<String,Object>(); Map<String,Object> beanMap = new HashMap<String,Object>(); Map<String,Object> MapForList = new HashMap<String,Object>(); List<Map<String,Object>> jsonList = new ArrayList<Map<String,Object>>(); MapForList.put("1","001"); MapForList.put("2","002"); jsonList.add(MapForList); beanMap.put("a","v1"); beanMap.put("b","v2"); jsonMap.put("key1","value1"); jsonMap.put("key2",beanMap); jsonMap.put("key3",jsonList); String jsonStr = JSON.toJSONString(jsonMap); System.out.println("javaBean序列化执行完毕!"); String jsonString ="{"key1":"value1","key2":{"a":"v1","b":"v2"},"key3":[{"1":"1","2":"2"}]}"; Map<String,Object> stringToMap = JSON.parseObject(jsonString,Map.class); System.out.println("jsonString反序列化完成!"); List<Map<String,Object>> list = (List<Map<String, Object>>) stringToMap.get("key3"); } }
2.2.jsonString合并
/** * 将srcJObjStr和addJObjStr合并,如果有重复字段,以addJObjStr为准 * @param srcJObjStr 原jsonObject字符串 * @param addJObjStr 需要加入的jsonObject字符串 * @return srcJObjStr */ private String combineJson(String srcJObjStr, String addJObjStr) throws JSONException { if(addJObjStr == null || addJObjStr.isEmpty()) { return srcJObjStr; } if(srcJObjStr == null || srcJObjStr.isEmpty()) { return addJObjStr; } JSONObject srcJObj = new JSONObject(srcJObjStr); JSONObject addJObj = new JSONObject(addJObjStr); combineJson(srcJObj, addJObj); return srcJObj.toString(); } @SuppressWarnings("unchecked") private JSONObject combineJson(JSONObject srcObj, JSONObject addObj) throws JSONException { Iterator<String> itKeys1 = addObj.keys(); String key, value; while(itKeys1.hasNext()){ key = itKeys1.next(); value = addObj.optString(key); srcObj.put(key, value); } return srcObj; }
上一篇:
Python 安装包管理工具 pip
下一篇:
Java压缩多层目录及文件