當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Fastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMap
生活随笔
收集整理的這篇文章主要介紹了
Fastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMap
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Fastjson實用工具類,List轉JSONString,List轉JSONArray,JSONArray轉List,JSONArray轉ArrayList,JSONObject轉HashMap
- 問題背景
- Fastjson轉換
- 心得
- Lyric:我們擁有
問題背景
因為經常用到fastjson,但fastjson里面有些轉換沒有,自己寫了一個工具類,方便快捷進行轉換
注意事項:
- 添加fastjson和common-lang3的依賴包
- 可以直接復制文中的代碼,也可以下載源碼進行參考
Fastjson轉換
1 FastjsonUtils工具轉換類
package com.yg.fastjson.utils;import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils;import java.util.*;/*** @Author suolong* @Date 2022/3/19 11:24* @Version 1.5*/ @Slf4j public final class FastjsonUtils {//fastjson格式轉換器private static SerializeConfig config;static {config = new SerializeConfig();config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));}private static final SerializerFeature[] features = {// 輸出空置字段SerializerFeature.WriteMapNullValue,// list字段如果為null,輸出為[],而不是nullSerializerFeature.WriteNullListAsEmpty,// 數值字段如果為null,輸出為0,而不是nullSerializerFeature.WriteNullNumberAsZero,// Boolean字段如果為null,輸出為false,而不是nullSerializerFeature.WriteNullBooleanAsFalse,// 字符類型字段如果為null,輸出為"",而不是nullSerializerFeature.WriteNullStringAsEmpty};/*** Object TO Json String 字符串輸出*/public static String toJSONString(Object object) {try {return JSON.toJSONString(object, config, features);} catch (Exception e) {log.error("JsonUtil | method=toJSON() | 對象轉為Json字符串 Error!" + e.getMessage(), e);}return null;}/*** Object TO Json String Json-lib兼容的日期輸出格式*/public static String toJSONLib(Object object) {try {return JSON.toJSONString(object, config, features);} catch (Exception e) {log.error("JsonUtil | method=toJSONLib() | 對象轉為Json字符串 Json-lib兼容的日期輸出格式 Error!" + e.getMessage(), e);}return null;}/*** 轉換為數組 Object*/public static Object[] toArray(String text) {try {return toArray(text, null);} catch (Exception e) {log.error("JsonUtil | method=toArray() | 將json格式的數據轉換為數組 Object Error!" + e.getMessage(), e);}return null;}/*** 轉換為數組 (可指定類型)*/public static <T> Object[] toArray(String text, Class<T> clazz) {try {return JSON.parseArray(text, clazz).toArray();} catch (Exception e) {log.error("JsonUtil | method=toArray() | 將json格式的數據轉換為數組 (可指定類型) Error!" + e.getMessage(), e);}return null;}/*** List轉換為JSONArray*/public static JSONArray toJSONArray(List<?> list) {try {String json = toJSONString(list);return JSONArray.parseArray(json);} catch (Exception e) {log.error("JsonUtil | method=toJSONArray() | 將list格式的數據轉換為JSONArray Object Error!" + e.getMessage(), e);}return null;}/*** 重載類型為String* Json 轉為 Jave Bean, 再使用Bean類型進行強轉*/public static <T> T toBean(String text, Class<T> clazz) {try {return JSON.parseObject(text, clazz);} catch (Exception e) {log.error("JsonUtil | method=toBean() | Json 轉為 Jave Bean Error!" + e.getMessage(), e);}return null;}/*** 重載類型為JSONObject* Json 轉為 Jave Bean, 再使用Bean類型進行強轉*/public static <T> T toBean(JSONObject text, Class<T> clazz) {try {String json = toJSONString(text);return toBean(json, clazz);} catch (Exception e) {log.error("JsonUtil | method=toBean() | Json 轉為 Jave Bean Error!" + e.getMessage(), e);}return null;}/*** 重載類型為String* Json 轉為 Map,JSON.parseObject轉換的類型為JSONObject,但是JSONObject實現了Map接口*/public static Map<?, ?> toMap(String json) {try {return JSON.parseObject(json);} catch (Exception e) {log.error("JsonUtil | method=toMap() | Json 轉為 Map {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為JSONObject* Json 轉為 Map,JSON.parseObject轉換的類型為JSONObject,但是JSONObject實現了Map接口*/public static Map<?, ?> toMap(JSONObject json) {try {return JSON.parseObject(JSON.toJSONString(json));} catch (Exception e) {log.error("JsonUtil | method=toMap() | Json 轉為 Map {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為String* Json 轉為 Map,JSON.parseObject轉換的類型為JSONObject,但是JSONObject實現了Map接口*/public static HashMap<?, ?> toHashMap(String json) {try {Map<?, ?> map = toMap(json);return new HashMap<>(map);} catch (Exception e) {log.error("JsonUtil | method=toMap() | Json 轉為 Map {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為JSONObject* Json 轉為 Map,JSON.parseObject轉換的類型為JSONObject,但是JSONObject實現了Map接口*/public static HashMap<?, ?> toHashMap(JSONObject json) {try {Map<?, ?> map = toMap(json);return new HashMap<>(map);} catch (Exception e) {log.error("JsonUtil | method=toMap() | Json 轉為 Map {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為String* Json 轉 List,Class 集合中泛型的類型,非集合本身,可json-lib兼容的日期格式*/public static <T> List<T> toList(String text, Class<T> clazz) {try {return JSON.parseArray(text, clazz);} catch (Exception e) {log.error("JsonUtil | method=toList() | Json 轉為 List {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為JSONObject* Json 轉 List,Class 集合中泛型的類型,非集合本身,可json-lib兼容的日期格式*/public static <T> List<T> toList(JSONArray text, Class<T> clazz) {try {String json = toJSONString(text);return toList(json, clazz);} catch (Exception e) {log.error("JsonUtil | method=toList() | Json 轉為 List {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為String* Json 轉 List,Class 集合中泛型的類型,非集合本身,可json-lib兼容的日期格式*/public static <T> ArrayList<T> toArrayList(String text, Class<T> clazz) {try {List<T> list = toList(text, clazz);assert list != null;return new ArrayList<>(list);} catch (Exception e) {log.error("JsonUtil | method=toList() | Json 轉為 List {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為JSONObject,clazz為list里面的類型* Json 轉 List,Class 集合中泛型的類型,非集合本身,可json-lib兼容的日期格式*/public static <T> ArrayList<T> toArrayList(JSONArray text, Class<T> clazz) {try {List<T> list = toList(text, clazz);assert list != null;return new ArrayList<>(list);} catch (Exception e) {log.error("JsonUtil | method=toList() | Json 轉為 List {},{}" + e.getMessage(), e);}return null;}/*** 重載類型為String* 從json字符串獲取指定key的字符串*/public static Object getValueFromJson(final String json, final String key) {try {if (StringUtils.isBlank(json) || StringUtils.isBlank(key)) {return null;}return JSON.parseObject(json).getString(key);} catch (Exception e) {log.error("JsonUtil | method=getStringFromJson() | 從json獲取指定key的字符串 Error!" + e.getMessage(), e);}return null;}/*** 重載類型為JSONObject* 從json字符串獲取指定key的字符串*/public static Object getValueFromJson(final JSONObject json, final String key) {try {String text = toJSONString(json);return getValueFromJson(text, key);} catch (Exception e) {log.error("JsonUtil | method=getStringFromJson() | 從json獲取指定key的字符串 Error!" + e.getMessage(), e);}return null;} }2 測試main函數
package com.yg.fastjson.service;import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.yg.fastjson.response.Response; import com.yg.fastjson.utils.FastjsonUtils; import com.yg.fastjson.utils.JsonUtils;import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;/*** @Author suolong* @Date 2022/3/18 17:55* @Version 1.0*/ public class FastjsonTest {public static void main(String[] args) {List<HashMap<Integer, Integer>> arrayList = new ArrayList<>();for (int i = 0; i < 5; i++) {HashMap<Integer, Integer> hashMap = new HashMap<>();hashMap.put(i + 11, i + 10);hashMap.put(i + 21, i + 10);hashMap.put(i + 31, i + 10);arrayList.add(hashMap);}//將List轉為JSONStringString jsonString = FastjsonUtils.toJSONString(arrayList);System.out.println(jsonString);//將List轉為JSONArrayJSONArray jsonArray = FastjsonUtils.toJSONArray(arrayList);System.out.println(jsonArray.toString());//將JSONArray轉為ListList<HashMap> hpList= FastjsonUtils.toList(jsonArray, HashMap.class);System.out.println(hpList.get(0).getClass());//將JSONArray轉為ArrayListArrayList<HashMap> arrayList1 = FastjsonUtils.toArrayList(jsonArray, HashMap.class);System.out.println(arrayList1.get(0).get(11+""));//將string轉為beanResponse<String> boy = Response.success("you are a cool boy");String s = JSON.toJSONString(boy);Response response = FastjsonUtils.toBean(s, Response.class);System.out.println(response);} }3 代碼中測試Bean轉換的response類
package com.yg.fastjson.response;import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletResponse; import java.io.Serializable;public class Response<T> implements Serializable {private static final long serialVersionUID = -1222614520893986846L;private T data;/*** 錯誤碼*/private String code;/*** 錯誤信息*/private String msg;public Response() {}public Response(T data, String code, String msg) {this.data = data;this.code = code;this.msg = msg;}public T getData() {return data;}public void setData(T data) {this.data = data;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public static <T> Response<T> success(T data){return new Response<T>(data, ResponseCode.SUCESS, "ok");}public static <T> Response<T> success(T data, ResultCode resultCode){return new Response<T>(data, resultCode.getCode(), resultCode.getMsg());}public static <T> Response<T> notFound(){return new Response<T>(null, ResponseCode.FAIL, "server error");}// public static <T> Response<T> internalError(){ // return new Response<T>(null, ResultCode.CODE_98.getCode(), ResultCode.CODE_98.getMsg()); // }/*** 系統異常,為了不影響客戶,返回數據未查的* @param <T>* @return*/public static <T> Response<T> internalError(){return new Response<T>(null, ResultCode.CODE_02.getCode(), ResultCode.CODE_02.getMsg());}public static <T> Response<T> internalError(String msg){//setResponseStatus(500);return new Response<T>(null, ResponseCode.FAIL, msg);}public static <T> Response<T> needLoginError(String msg){setResponseStatus(500);return new Response<T>(null, ResponseCode.NEEDLOGIN, msg);}private static void setResponseStatus(int i) {ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();if (servletRequestAttributes == null) {//log.warn("failed to set response, because can't get HttpServletResponse");return;}final HttpServletResponse response = servletRequestAttributes.getResponse();if (response == null) {//log.warn("failed to set response, because can't get HttpServletResponse");return;}response.setStatus(i);}@Overridepublic String toString() {return "Response [data:" + data + ", code:" + code + ", message:" + msg + "]";}} package com.yg.fastjson.response;public class ResponseCode {/*** 表明該請求被成功地完成,所請求的資源發送到客戶端。*/public static final String SUCESS = "200";/*** 系統執行錯誤*/public static final String FAIL = "500";/*** 系統執行錯誤*/public static final String NEEDLOGIN = "401";} package com.yg.fastjson.response;public enum ResultCode {//00:成功,01:入參存在非法null,02:數據未查得,98:系統異常CODE_00("00","成功"),CODE_01("01","入參存在非法null"),CODE_02("02","數據未查得"),CODE_03("03","非規定的調用時間"),CODE_98("98","系統異常"),CODE_401("401","未登錄");private String code;private String msg;ResultCode(String code, String msg) {this.code = code;this.msg = msg;}public String getCode() {return code;}public String getMsg() {return msg;} }心得
- 這個工具類挺好用的,有新的轉法我會及時更新
作為程序員第 78 篇文章,每次寫一句歌詞記錄一下,看看人生有幾首歌的時間,wahahaha …
Lyric:我們擁有
總結
以上是生活随笔為你收集整理的Fastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMap的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python怎么读单词和古文,用文言文写
- 下一篇: 裸机中代码书写的细节总结