常用JSON工具类JsonUtil封装

前言

项目中经常会有String转Object以及Object转Json字符串的需求,故封装一个常用Json工具类

Maven依赖

    <dependency>
      <groupId>org.codehaus.jacksongroupId>
      <artifactId>jackson-mapper-aslartifactId>
      <version>1.9.13version>
    dependency>

如果项目没有使用Maven可以直接下载jar包

↓↓↓

jar包下载地址

package com.suddev.util;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * Jackson工具类
 *
 * @author suddev
 * @create 2017-11-25 2:18 PM
 **/
public class JsonUtil1 {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 对象字段全部列入
        objectMapper.setSerializationInclusion(Inclusion.NON_DEFAULT);

        // 取消默认转换timestamps形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);

        // 忽略空bean转json的错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);

        // 统一日期格式yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));

        // 忽略在json字符串中存在,但是在java对象中不存在对应属性的情况
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    /**
     * Object转json字符串
     * @param obj
     * @param 
     * @return
     */
    public static  String obj2String(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            System.out.println("Parse object to String error");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Object转json字符串并格式化美化
     * @param obj
     * @param 
     * @return
     */
    public static  String obj2StringPretty(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
            System.out.println("Parse object to String error");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * string转object
     * @param str json字符串
     * @param clazz 被转对象class
     * @param 
     * @return
     */
    public static  T string2Obj(String str,Class clazz){
        if (StringUtils.isEmpty(str) || clazz == null){
            return null;
        }
        try {
            return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
        } catch (IOException e) {
            System.out.println("Parse String to Object error");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * string转object
     * @param str json字符串
     * @param typeReference 被转对象引用类型
     * @param 
     * @return
     */
    public static  T string2Obj(String str, TypeReference typeReference){
        if (StringUtils.isEmpty(str) || typeReference == null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)? str :objectMapper.readValue(str,typeReference));
        } catch (IOException e) {
            System.out.println("Parse String to Object error");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * string转object 用于转为集合对象
     * @param str json字符串
     * @param collectionClass 被转集合class
     * @param elementClasses 被转集合中对象类型class
     * @param 
     * @return
     */
    public static  T string2Obj(String str,Class collectionClass,Class... elementClasses){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
        try {
            return objectMapper.readValue(str,javaType);
        } catch (IOException e) {
            System.out.println("Parse String to Object error");
            e.printStackTrace();
            return null;
        }
    }
}

测试代码

case1 obj转json

public static void main(String[] args) {
        User user = new User();
        user.setUsername("suddev");
        user.setId(123);
        String s = JsonUtil.obj2String(user);
        System.out.println(s);
    }

常用JSON工具类JsonUtil封装_第1张图片

case2 输出美化后的json字符串

public static void main(String[] args) {
        User user = new User();
        user.setUsername("suddev");
        user.setId(123);
        String s = JsonUtil1.obj2StringPretty(user);
        System.out.println(s);
    }

常用JSON工具类JsonUtil封装_第2张图片

case3 json字符串转obj

public static void main(String[] args) {
        String s = "{\"id\":123,\"username\":\"suddev\"}";
        User user = JsonUtil.string2Obj(s,User.class);
    }

常用JSON工具类JsonUtil封装_第3张图片

case4 使用TypeReference转换复杂对象

public static void main(String[] args) {
        User u1 = new User();
        u1.setUsername("aaa");u1.setId(1);
        User u2 = new User();
        u2.setUsername("bbb");u2.setId(2);
        List userList = Lists.newArrayList();
        userList.add(u1);userList.add(u2);
        String userListStr = JsonUtil.obj2StringPretty(userList);
        List userListObj = JsonUtil.string2Obj(userListStr, new TypeReference>() {});
    }

常用JSON工具类JsonUtil封装_第4张图片

case5 更简单直接的复杂对象转换方法

public static void main(String[] args) {
        User u1 = new User();
        u1.setUsername("aaa");u1.setId(1);
        User u2 = new User();
        u2.setUsername("bbb");u2.setId(2);
        List userList = Lists.newArrayList();
        userList.add(u1);userList.add(u2);
        String userListStr = JsonUtil.obj2StringPretty(userList);
        // List userListObj = JsonUtil.string2Obj(userListStr, new TypeReference>() {});
        // 依次传入集合以及集合中对象类型的class
        List userListObj2 = JsonUtil.string2Obj(userListStr,List.class,User.class);
    }

常用JSON工具类JsonUtil封装_第5张图片

方便项目中使用将System.out替换为log的版本

/**
 * Jackson工具类
 *
 * @author suddev
 * @create 2017-11-25 2:18 PM
 **/
@Slf4j
public class JsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 对象字段全部列入
        objectMapper.setSerializationInclusion(Inclusion.NON_DEFAULT);

        // 取消默认转换timestamps形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);

        // 忽略空bean转json的错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);

        // 统一日期格式yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));

        // 忽略在json字符串中存在,但是在java对象中不存在对应属性的情况
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    public static  String obj2String(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse object to String error",e);
            return null;
        }
    }

    public static  String obj2StringPretty(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse object to String error",e);
            return null;
        }
    }

    public static  T string2Obj(String str,Class clazz){
        if (StringUtils.isEmpty(str) || clazz == null){
            return null;
        }
        try {
            return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    public static  T string2Obj(String str, TypeReference typeReference){
        if (StringUtils.isEmpty(str) || typeReference == null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)? str :objectMapper.readValue(str,typeReference));
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    public static  T string2Obj(String str,Class collectionClass,Class... elementClasses){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
        try {
            return objectMapper.readValue(str,javaType);
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }
}

你可能感兴趣的:(java)