java常用工具类—— JSON处理工具类

Posted liusandy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java常用工具类—— JSON处理工具类相关的知识,希望对你有一定的参考价值。

package com.springboot.commons.utils;

import com.springboot.commons.scan.JacksonObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

/**
 * @author Lius
 * @date 2018/10/26 14:34
 * @description JSON 工具类
 */
public class JsonUtils {
    private static final String JSONARRAY = "net.sf.json.JSONArray";

    public JsonUtils() {
    }

    private static ObjectMapper getInstance() {
        return JacksonHolder.INSTANCE;
    }

    private static class JacksonHolder {
        private static ObjectMapper INSTANCE = new JacksonObjectMapper();
    }

    /**
     * 将对象序列化成JSON对象
     *
     * @param object java对象
     * @author Lius
     * @date 2018/10/26 14:37
     */
    public static String toJson(Object object) {
        try {
            return getInstance().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 将json反序列化成java对象
     *
     * @param jsonString 需要序列化的json字符串
     * @param valueType  序列化成的对象
     * @author Lius
     * @date 2018/10/26 14:42
     */
    public static <T> T parse(String jsonString, Class<T> valueType) {
        try {
            return getInstance().readValue(jsonString, valueType);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 判断所有json字段是否全为空
     *
     * @param jsonObj JSON 对象
     * @author Lius
     * @date 2018/10/26 14:51
     */
    public boolean isAllFieldNotNull(Object jsonObj) throws Exception {
        boolean flag = false;
        if (jsonObj == null) {
            return false;
        }
        String type = jsonObj.getClass().getName();
        // Object对象
        if (!JSONARRAY.equals(type)) {
            JSONObject jsonObject = JSONObject.fromObject(jsonObj);
            Iterator iterator = jsonObject.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                if (jsonObject.get(key) != null && !"".equals(jsonObject.get(key))) {
                    flag = true;
                }
            }
            return flag;
        } else {
            JSONArray jsonArray = JSONArray.fromObject(jsonObj);
            for (Object object : jsonArray) {
                JSONObject jsonObject = JSONObject.fromObject(object);
                Iterator iterator = jsonObject.keys();
                while (iterator.hasNext()) {
                    String key = (String) iterator.next();
                    if (jsonObject.get(key) != null && !"".equals(jsonObject.get(key))) {
                        flag = true;
                    }
                }
                return flag;
            }
        }
        return true;
    }
/**
     * 把JSON字符串转换为Map形式
     * @author Lius
     * @date 2018/11/8 9:19
    */
    public static Map<String, Object> jSON2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject json = JSONObject.fromObject(jsonStr);
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Iterator it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    Object json2 = it.next();
                    list.add(jSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    public static void main(String[] args) {
        String json = "{"name":"zhangsan","age":20,"loginName":"loginName","password":"[email protected]"}";

    }

}
  • JacksonObjectMapper 代码如下
package com.springboot.commons.scan;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 解决Jackson 差8小时的问题
 * @author Lius
 */
@Component("jacksonObjectMapper")
public class JacksonObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 4288193147502386170L;

    private static final Locale CHINA = Locale.CHINA;
    
    public JacksonObjectMapper() {
        this.setLocale(CHINA);
        this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", CHINA));
        this.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    }

}

以上是关于java常用工具类—— JSON处理工具类的主要内容,如果未能解决你的问题,请参考以下文章

Java常用工具类---image图片处理工具类Json工具类

elasticsearch代码片段,及工具类SearchEsUtil.java

solr分布式索引实战分片配置读取:工具类configUtil.java,读取配置代码片段,配置实例

Json解析工具类

Json序列化java工具类

处理json的工具类({本类为处理json的工具类})