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

导读:本篇文章讲解 Fastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMap,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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

问题背景

因为经常用到fastjson,但fastjson里面有些转换没有,自己写了一个工具类,方便快捷进行转换
注意事项:

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,输出为[],而不是null
            SerializerFeature.WriteNullListAsEmpty,
            // 数值字段如果为null,输出为0,而不是null
            SerializerFeature.WriteNullNumberAsZero,
            // Boolean字段如果为null,输出为false,而不是null
            SerializerFeature.WriteNullBooleanAsFalse,
            // 字符类型字段如果为null,输出为"",而不是null
            SerializerFeature.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转为JSONString
        String jsonString = FastjsonUtils.toJSONString(arrayList);
        System.out.println(jsonString);

        //将List转为JSONArray
        JSONArray jsonArray = FastjsonUtils.toJSONArray(arrayList);
        System.out.println(jsonArray.toString());

        //将JSONArray转为List
        List<HashMap>  hpList= FastjsonUtils.toList(jsonArray, HashMap.class);
        System.out.println(hpList.get(0).getClass());

        //将JSONArray转为ArrayList
        ArrayList<HashMap> arrayList1 = FastjsonUtils.toArrayList(jsonArray, HashMap.class);
        System.out.println(arrayList1.get(0).get(11+""));

        //将string转为bean
        Response<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);
    }

    @Override
    public 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 …
Fastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMapFastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMapFastjson实用工具类,List转JSONString,List转JSONArray,JSONArray转List,JSONArray转ArrayList,JSONObject转HashMap

Lyric:我们拥有

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/110797.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!