Fastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMap

article/2025/10/12 22:26:27

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:我们拥有


http://chatgpt.dhexx.cn/article/Xf4cFdOI.shtml

相关文章

java中好用的list转json的工具hutool

java中好用的list转json的工具hutool 最近做服务器接口开发的时候遇到的小问题&#xff0c;数据库查询之后的数据怎样快捷的转化为json数据&#xff0c;第一时间想到了查库 查了挺久的&#xff0c;好多都是用代码实现&#xff0c;比较懒&#xff0c;这方面内容代码实现的偏多…

list转json

Struts2中list转换为json jar包下载地址 所需jar包&#xff0c;如下图&#xff1a; 实现代码&#xff0c;这里以execute方法为例&#xff1a; Overridepublic String execute() throws Exception {//1.调用Service根据typecode获得数据字典对象listList<BaseDict> l…

json与对象互转:json转实体类、实体类转json、json转List、List转json

目录 使用fastjson和Gson实现&#xff1a;实体类与json互转&#xff0c;List与json互转1. 实体类转json数据1.1 fastjson:1.2 Gson&#xff1a; 2. json转实体类2.1 fastjson&#xff1a;2.2 Gson: 3. List集合转json3.1 fastjson:3.2 Gson&#xff1a; 4. JSON转List集合4.1 f…

方法重写与重载的区别

1、方法重载 重载&#xff08;Overload&#xff09; 是在一个类里面&#xff0c;但方法的参数不同&#xff0c;包括参数的类型或者个数&#xff0c;返回值的类型可相同可不同。每一个重载的方法都有一个独一无二的参数列表。 最常用的地方就是构造器的重载。 2.方法重写 重写…

C#重写和重载的区别分析

一、前言 接触面向对象的思想已经有一段时光了&#xff0c;为什么要学习面向对象呢&#xff1f;因为面向对象具有可复用性、可维护性、可扩展性等优点。 刚学习完C#之后&#xff0c;难免会对重载和重写傻傻分不清楚。如今通过查阅资料对这两者有了一个大概的理解&#x…

【Java SE】重写和重载的区别

重写: 重写&#xff08;Override&#xff09;是父类与子类之间多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数&#xff0c;我们说该方法被重写 (Override)。子类的对象使用这个方法时&#xff0c;将调用子类中的定义&#xff0c;对它而言&#xff0c;父…

方法重写和重载的区别

一、方法重写(0veriding) 在Java程序中&#xff0c;类的继承关系可以产生一个子类&#xff0c;子类继承父类&#xff0c;它具备了父类所有的特征&#xff0c;继承了父类所有的方法和变量。 子类可以定义新的特征&#xff0c;当子类需要修改父类的一些方法进行扩展&#xff0c…

面试官:Java的重写和重载有什么区别?

老读者都知道了&#xff0c;七年前&#xff0c;我从美女很多的苏州回到美女更多的洛阳&#xff08;美化了&#xff09;&#xff0c;抱着一幅“从二线城市退居三线城市”的心态&#xff0c;投了不少简历&#xff0c;也“约谈”了不少面试官&#xff0c;但仅有两三个令我感到满意…

JAVA重写和重载的区别

文章目录 [toc] 问&#xff1a; Java 重载与重写是什么&#xff1f;有什么区别&#xff1f;问&#xff1a;Java 构造方法能否被重写和重载&#xff1f;问&#xff1a;下面程序的运行结果是什么&#xff0c;为什么&#xff1f; 问&#xff1a; Java 重载与重写是什么&#xff1f…

matlab 中histogram,hist的用法

x randn(1000,1); edges [-10 -2:0.25:2 10]; h histogram(x,edges);这是指定区间的&#xff1b;第一个是-10&#xff0c;2 histogram参考链接 hist是用区间的作为直方图的中心 hist参考链接

文献引文分析利器HistCite使用教程(附精简易用免安装Pro版本下载)

如果你选修过中国科学技术大学罗昭锋老师的《文献管理与信息分析》&#xff0c;那么你一定不会对HistCite 感到陌生&#xff0c;这是一款非常强大的引文分析工具&#xff0c;可以快速绘制出某个研究领域的发展脉络&#xff0c;快速锁定某个研究方向的重要文献和学术大牛&#x…

文献综述搜索利器——HistCite

HistCite 1. LCR2. GCS3. LCS4. CR5. 说明6. 参考 1. LCR Local Cited References is the number of references citing local papers. By clicking on “LCR”,you can sort the collection by this score. By clicking on the LCR number, you can see a list of thepapers …

2021-01-19(学堂云)文献管理与信息分析期末考卷

&#xff08;学堂云&#xff09;文献管理与信息分析期末考卷 1为知笔记中群组的核心功能是?2以下哪种软件可以帮我们追踪到最新资讯?3连接goole的时候&#xff0c;输入http://google.com,网页会自动跳到http://google .com.hk,解决方案是在htttp://google.com后面输入哪三个…

引文分析软件histcite简介

本文写于多年之前。附上能个近期学生写的补充&#xff0c;以及改进版的小程序。 https://zhuanlan.zhihu.com/p/20902898 这是上学期选修我课程的王庆撰写文件&#xff0c;并改写了一下程序&#xff0c;导入更加方便。 附王庆改写的程序下载链接&#xff1a;http://pan.baidu…

HistCite软件导入文献

转自&#xff1a;了凡春秋 上一篇博客介绍了HistCite软件的一些情况和使用中的一个问题的解决方法。这篇说一下这个软件的使用方法吧&#xff0c;其实最关键的就是导入文献&#xff0c;剩下的就是各种排序查看、产生引用关系图锁定重要文献。 HistCite导入的文献必须来自于WoK数…

【学术灯塔】文献可视化分析软件:HistCite、vosviewer、Citespace

相信大家的文献管理效率大大提高。那么在接触一个新研究方向&#xff0c;面对浩如烟海的文献感到无从下手的时候&#xff0c;我们又该如何对文献进行更深度的分析呢&#xff1f;本期&#xff0c;小编就给大家介绍三个文献可视化分析的软件&#xff0c;帮助大家又快又准地锁定该…

文献引文分析利器 HistCite 详细使用教程

如果你选修过中国科学技术大学罗昭锋老师的《文献管理与信息分析》&#xff0c;那么你一定不会对HistCite 感到陌生&#xff0c;这是一款非常强大的引文分析工具&#xff0c;可以快速绘制出某个研究领域的发展脉络&#xff0c;快速锁定某个研究方向的重要文献和学术大牛&#x…

HistCite学习

刚进入到一个新的方向时,需要先读一读这个这个方向的经典文献,并分析一下这个方向的研究现状。一种最常见的做法是下载几篇该方向的综述论文,并通过综述文献的参考文献和被引文献来进一步的挖掘新的文献。但是,这种方法需要读的文献较多,那么有没有更便捷的方式来找到这些…

【工具】文献分析工具histcite的简单使用

查找文献分析方法时候看到的&#xff1a; 图片来源&#xff1a;百度文库 总的操作流程参考自&#xff1a;罗昭锋&#xff1a;引文分析软件histcite简介 1. wos检索 检索结果: 1,360 (来自 Web of Science 核心合集) 您的检索: TS(altimeter OR altimetry ) AND TSgravity时…