JsonUtil.java

package com.xxx.common.util;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.map.ser.StdSerializerProvider;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JSON utility
 * @author bc
 *
 */
public final class JsonUtil {

    /**
     * log
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    /**
     *
     */
    private JsonUtil() {

    }

    /**
     *
     */
    static final ObjectMapper OBJECT_MAPPER;

    static {
        StdSerializerProvider sp = new StdSerializerProvider();
        OBJECT_MAPPER = new ObjectMapper(null, sp, null);
        OBJECT_MAPPER.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL);
        OBJECT_MAPPER.getSerializationConfig().with(Feature.SORT_PROPERTIES_ALPHABETICALLY);
        OBJECT_MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    /**
     * JSON串转换为Java泛型对象,可以是各种类型
     *
     * @param <T> return type
     * @param jsonString JSON
     * @param tr TypeReference,例如: new TypeReference< List<FamousUser> >(){}
     * @return List对象列表
     */
    @SuppressWarnings("unchecked")
    public static <T> T json2GenericObject(String jsonString, TypeReference<T> tr) {
        if (!StringUtils.isBlank(jsonString)) {
            try {
                return (T) OBJECT_MAPPER.readValue(jsonString, tr);
            } catch (Exception e) {
                LOGGER.warn("json error:" + e.getMessage());
            }
        }
        return null;
    }

    /**
     * Java对象转JSON字符串
     *
     * @param object Java对象,可以是对象,数组,List,Map等
     * @return JSON 字符串
     */
    public static String toJson(Object object) {
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            LOGGER.warn("json error:" + e.getMessage());
        }
        return null;

    }

    /**
     * JSON字符串转Java对象
     *
     * @param jsonString JSON
     * @param c class
     * @return
     */
    public static Object json2Object(String jsonString, Class<?> c) {
        if (!StringUtils.isBlank(jsonString)) {
            try {
                return OBJECT_MAPPER.readValue(jsonString, c);
            } catch (Exception e) {
                LOGGER.warn("json error:" + e.getMessage());
            }

        }
        return null;
    }

    /**
     * 验证字符串是否为json格式
     *
     * @param json
     * @return
     */
    public static boolean isValidJson(final String json) {
        boolean valid = false;
        try {
           final JsonParser parser = new ObjectMapper().getJsonFactory()
                 .createJsonParser(json);
           while (parser.nextToken() != null) {
           }
           valid = true;
        } catch (JsonParseException jpe) {
            return valid;
        } catch (IOException ioe) {
            return valid;
        }
        return valid;
     }
}
时间: 2024-10-29 03:14:42

JsonUtil.java的相关文章

JSONUtil(JAVA对象/List与json互转,xml与json互转)

package com.chauvet.utils.json; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.J

解决用户自生成meta导入kylin后报错问题Can not deserialize instance of java.lang.String[] out of VALUE_STRING token

报错栈: 2017-06-22 20:48:07,101 ERROR [http-bio-7070-exec-5] cube.CubeManager:947 : Error during load cube instance, skipping : /cube/energon_dm_admission_record_fact_01.json java.lang.IllegalStateException: Failed to init CubeDescManager from [email pr

org.apache.catalina.connector.Request.parseParameters(Request.java:2446) NullPointerException异常处理

1.环境 tomcat6.0.8 + jdk6 + struts1 2.问题的产生 页面有两个异常的请求 http://127.0.0.1/project/a.action?do=testA&m=10 http://127.0.0.1/project/a.action?do=testB&m=10 两个请求几乎同步到达server.结果出现异常: java.lang.NullPointerException at org.apache.catalina.connector.Request.p

org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException异常解决

org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246) org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178) org.apache.struts2.json.JSONWriter.p

java:redis(java代码操作redis)

1.redis_demo Maven  ItemMapper.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespa

java笔记整理

Java 笔记整理 包含内容     Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, Ejb, java和模式 Linux/Unix笔记 inode :存储编号(地址) ls -k:查看磁盘分区 ls -li:显示当前文件的inode号. 目录的大小跟文件的大小有关,跟目录里的文件(目录)数量无关. 一行多个命令的话,中间用分号分开.如:pwd;cal;date last | grep

ElasticSearch Java Api -创建索引

ElasticSearch JAVA API官网文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html 一.生成JSON 创建索引的第一步是要把对象转换为JSON字符串.官网给出了四种创建JSON文档的方法: 1.1手写方式生成 String json = "{" + "\"user\":\"kimchy\"

ason 和 Java 对象转化示例

1.工程 2.代码: JsonUtil.java package com.my.json; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonUtil { /** * 从一个JSON 对象字符格式中得到一个java对象 * * @param jsonString * json字符串 * *

Java中关于Json对象类型和字符串类型之间互相转化的问题

Java中关于Json格式转化Object,Map,Collection类型和String类型之间的转化在我们实际项目中应用的很是普遍和广泛.最近工作的过程中也是经常有,因此,自己封装了一个JsonUtil.java类. 所需要的jar包:slf4j-jdk14-1.5.6.jar,slf4j-api-1.5.6.jar------>此两个jar包是slf4j日志jar包 jackson-annotations-2.1.1.jar,jackson-core-2.1.1.jar,jackson-d