import java.util.ArrayList;
import java.util.List;
import java.util.Map; import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken; public class GsonUtil {
//不用创建对象,直接使用Gson.就可以调用方法
private static Gson gson = null;
//判断gson对象是否存在了,不存在则创建对象
static {
if (gson == null) {
//gson = new Gson();
//当使用GsonBuilder方式时属性为空的时候输出来的json字符串是有键值key的,显示形式是"key":null,而直接new出来的就没有"key":null的
gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
}
}
//无参的私有构造方法
private GsonUtil() {
} /**
* 将对象转成json格式
*
* @param object
* @return String
*/
public static String GsonString(Object object) {
String gsonString = null;
if (gson != null) {
gsonString = gson.toJson(object);
}
return gsonString;
} /**
* 将json转成特定的cls的对象
*
* @param gsonString
* @param cls
* @return
*/
public static <T> T GsonToBean(String gsonString, Class<T> cls) {
T t = null;
if (gson != null) {
//传入json对象和对象类型,将json转成对象
t = gson.fromJson(gsonString, cls);
}
return t;
} /**
* json字符串转成list
*
* @param gsonString
* @param cls
* @return
*/
public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
List<T> list = null;
if (gson != null) {
//根据泛型返回解析指定的类型,TypeToken<List<T>>{}.getType()获取返回类型
list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
}.getType());
}
return list;
} /**
* json字符串转成list中有map的
*
* @param gsonString
* @return
*/
public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
List<Map<String, T>> list = null;
if (gson != null) {
list = gson.fromJson(gsonString,
new TypeToken<List<Map<String, T>>>() {
}.getType());
}
return list;
} /**
* json字符串转成map的
*
* @param gsonString
* @return
*/
public static <T> Map<String, T> GsonToMaps(String gsonString) {
Map<String, T> map = null;
if (gson != null) {
map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
}.getType());
}
return map;
}
}
public class JacksonUtils {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    private JacksonUtils() {

    }

    public static ObjectMapper getInstance() {
return objectMapper;
} /**
* javaBean、列表数组转换为json字符串
*/
public static String obj2json(Object obj) throws Exception {
return objectMapper.writeValueAsString(obj);
} /**
* javaBean、列表数组转换为json字符串,忽略空值
*/
public static String obj2jsonIgnoreNull(Object obj) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(obj);
} /**
* json 转JavaBean
*/ public static <T> T json2pojo(String jsonString, Class<T> clazz) throws Exception {
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
return objectMapper.readValue(jsonString, clazz);
} /**
* json字符串转换为map
*/
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.readValue(jsonString, Map.class);
} /**
* json字符串转换为map
*/
public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) throws Exception {
Map<String, Map<String, Object>> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, T>>() {
});
Map<String, T> result = new HashMap<String, T>();
for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
}
return result;
} /**
* 深度转换json成map
*
* @param json
* @return
*/
public static Map<String, Object> json2mapDeeply(String json) throws Exception {
return json2MapRecursion(json, objectMapper);
} /**
* 把json解析成list,如果list内部的元素存在jsonString,继续解析
*
* @param json
* @param mapper 解析工具
* @return
* @throws Exception
*/
private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception {
if (json == null) {
return null;
} List<Object> list = mapper.readValue(json, List.class); for (Object obj : list) {
if (obj != null && obj instanceof String) {
String str = (String) obj;
if (str.startsWith("[")) {
obj = json2ListRecursion(str, mapper);
} else if (obj.toString().startsWith("{")) {
obj = json2MapRecursion(str, mapper);
}
}
} return list;
} /**
* 把json解析成map,如果map内部的value存在jsonString,继续解析
*
* @param json
* @param mapper
* @return
* @throws Exception
*/
private static Map<String, Object> json2MapRecursion(String json, ObjectMapper mapper) throws Exception {
if (json == null) {
return null;
} Map<String, Object> map = mapper.readValue(json, Map.class); for (Map.Entry<String, Object> entry : map.entrySet()) {
Object obj = entry.getValue();
if (obj != null && obj instanceof String) {
String str = ((String) obj); if (str.startsWith("[")) {
List<?> list = json2ListRecursion(str, mapper);
map.put(entry.getKey(), list);
} else if (str.startsWith("{")) {
Map<String, Object> mapRecursion = json2MapRecursion(str, mapper);
map.put(entry.getKey(), mapRecursion);
}
}
} return map;
} /**
* 与javaBean json数组字符串转换为列表
*/
public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz) throws Exception { JavaType javaType = getCollectionType(ArrayList.class, clazz);
List<T> lst = (List<T>) objectMapper.readValue(jsonArrayStr, javaType);
return lst;
} /**
* 获取泛型的Collection Type
*
* @param collectionClass 泛型的Collection
* @param elementClasses 元素类
* @return JavaType Java类型
* @since 1.0
*/
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
} /**
* map 转JavaBean
*/
public static <T> T map2pojo(Map map, Class<T> clazz) {
return objectMapper.convertValue(map, clazz);
} /**
* map 转json
*
* @param map
* @return
*/
public static String mapToJson(Map map) {
try {
return objectMapper.writeValueAsString(map);
} catch (Exception e) {
e.printStackTrace();
}
return "";
} /**
* map 转JavaBean
*/
public static <T> T obj2pojo(Object obj, Class<T> clazz) {
return objectMapper.convertValue(obj, clazz);
}
}
/**
* fastjson工具类
* @version:1.0.0
*/
public class FastJsonUtils { private static final SerializeConfig config; static {
config = new SerializeConfig();
config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
} private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null
}; public static String toJSONString(Object object) {
return JSON.toJSONString(object, config, features);
} public static String toJSONNoFeatures(Object object) {
return JSON.toJSONString(object, config);
} public static Object toBean(String text) {
return JSON.parse(text);
} public static <T> T toBean(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
} // 转换为数组
public static <T> Object[] toArray(String text) {
return toArray(text, null);
} // 转换为数组
public static <T> Object[] toArray(String text, Class<T> clazz) {
return JSON.parseArray(text, clazz).toArray();
} // 转换为List
public static <T> List<T> toList(String text, Class<T> clazz) {
return JSON.parseArray(text, clazz);
} /**
* 将javabean转化为序列化的json字符串
* @param keyvalue
* @return
*/
public static Object beanToJson(KeyValue keyvalue) {
String textJson = JSON.toJSONString(keyvalue);
Object objectJson = JSON.parse(textJson);
return objectJson;
} /**
* 将string转化为序列化的json字符串
* @param keyvalue
* @return
*/
public static Object textToJson(String text) {
Object objectJson = JSON.parse(text);
return objectJson;
} /**
* json字符串转化为map
* @param s
* @return
*/
public static Map stringToCollect(String s) {
Map m = JSONObject.parseObject(s);
return m;
} /**
* 将map转化为string
* @param m
* @return
*/
public static String collectToString(Map m) {
String s = JSONObject.toJSONString(m);
return s;
} }

Gson/Jackson/FastJson工具类的更多相关文章

  1. fastJson工具类

    jar:fast.jar 依赖: <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId&g ...

  2. 阿里fastjson工具类

    package com.common.utils.jsonUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JS ...

  3. Android Gson解析json工具类封装

    package com.springSecurity.gson; import java.util.ArrayList; import java.util.List; import java.util ...

  4. Jackson常用工具类

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11983194.html Demo package org.fool.util; import com. ...

  5. 工具类-Fastjson入门使用

    简介 什么是Fastjson? fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到Java ...

  6. Jackson 工具类使用及配置指南

    目录 前言 Jackson使用工具类 Jackson配置属性 Jackson解析JSON数据 Jackson序列化Java对象 前言 Json数据格式这两年发展的很快,其声称相对XML格式有很对好处: ...

  7. Jackson工具类使用及配置指南、高性能配置(转)

    Jackson使用工具类 通常,我们对JSON格式的数据,只会进行解析和封装两种,也就是JSON字符串--->Java对象以及Java对象--->JSON字符串. public class ...

  8. Gson、FastJson、json-lib对比与实例

    一.各个JSON技术的对比(本部分摘抄自http://www.cnblogs.com/kunpengit/p/4001680.html): 1.json-libjson-lib最开始的也是应用最广泛的 ...

  9. FastJsonUtils工具类

    fastjson是由alibaba开源的一套json处理器.与其他json处理器(如Gson,Jackson等)和其他的Java对象序列化反序列化方式相比,有比较明显的性能优势. 版权声明:本文为博主 ...

随机推荐

  1. [Arc102B]All Your Paths are Different Lengths_构造_二进制拆分

    All Your Paths are Different Lengths 题目链接:https://atcoder.jp/contests/arc102/tasks/arc102_b 题解: 构造题有 ...

  2. EXCEL 查找某个字符在字符串中最后一次出现的位置

    在EXCEL文档里想从很长的文件路径中取得文件名,[数据]→[分列]是个不错的选择,但用函数会显得更高大上一些. 首先,需要获取最后一个"\"所在的位置. 方法1: FIND(&q ...

  3. oracle中Blob、Clob、Varchar之间的互相转换

    以下是oracle中Blob.Clob.Varchar之间的互相转换(都是百度找的,亲测可用) Blob转Varchar2: CREATE OR REPLACE FUNCTION blob_to_va ...

  4. Scrapy setup.py 各参数详解

    实际上Scrapyd的打包工具用到了setuptools,而打包参数主要是在setuptools里面的setup函数中设置. ************************************* ...

  5. Python 中 参数* 和 **

    举个例子就知道了 class test(): def __init__(self, *a, **b): print(a) print(b) print(b.get('test')) tester = ...

  6. mysql中比较实用的几个函数

    1.曾有这样的需求: 可以使用如下函数: 语法:FIND_IN_SET(str,strlist). 定义: 1. 假如字符串str在由N子链组成的字符串列表strlist中,则返回值的范围在1到N之间 ...

  7. Problems to be upsolved

    Donation 官方题解尚未看懂. comet oj contest15 双11特惠hard Mobitel Small Multiple 题解 为什么可以如此缩点? Candy Retributi ...

  8. django 中静态文件项目加载问题

    问题描述: django项目中创建了多个app后,每个app中都有对应的static静态文件.整个项目运行时这些静态文件的加载就是一个问题,因为整个项目我只参与了一部分,项目部署之类的并没有参与.我写 ...

  9. 一文看懂java io系统 (转)

    出处:  一文看懂java io系统   学习java IO系统,重点是学会IO模型,了解了各种IO模型之后就可以更好的理解java IO Java IO 是一套Java用来读写数据(输入和输出)的A ...

  10. 使用python django快速搭建微信公众号后台

    前言 使用python语言,django web框架,以及wechatpy,快速完成微信公众号后台服务的简易搭建,做记录于此. wechatpy是一个python的微信公众平台sdk,封装了被动消息和 ...