`

json与Ojbect互相转换

    博客分类:
  • JSON
 
阅读更多

json与Ojbect互相转换,用到的第三方库为:jackson-mapper-asl-*.jar

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

public class JsonUtil {

    /**
     * 
     * 此方法描述的是:根据key取得相应的值
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return String
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonGenerationException
     */
    public static String getString(Map<String, Object> map, String key) throws JsonGenerationException,
            JsonMappingException, IOException {
        try {
            return (String) map.get(key);
        }
        catch (Exception e) {
            return JsonUtil.toString(map.get(key));
        }
    }

    /**
     * 
     * 此方法描述的是:取得list
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return List<Map<String, Object>>
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @SuppressWarnings("unchecked")
    public static List<Map<String, Object>> getList(Map<String, Object> map, String key) throws JsonParseException,
            JsonMappingException, IOException {
        if (null == map) {
            return null;
        }
        try {
            return (List<Map<String, Object>>) map.get(key);
        }
        catch (Exception e) {
            return JsonUtil.toList(map.get(key));
        }

    }

    /**
     * 
     * 此方法描述的是:取得list
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return Map<String, Object>
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getMap(Map<String, Object> map, String key) throws JsonParseException,
            JsonMappingException, IOException {
        try {
            return (Map<String, Object>) map.get(key);
        }
        catch (Exception e) {
            return JsonUtil.toBean(map.get(key), Map.class);
        }

    }

    /**
     * 
     * 此方法描述的是:根据key取值int
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @param defaultValue
     *            默认值
     * @return int
     */
    public static int getInt(Map<String, Object> map, String key, int defaultValue) {
        try {
            return (Integer) map.get(key);
        }
        catch (Exception e) {
            try {
                return Integer.parseInt(JsonUtil.toString(map.get(key)));
            }
            catch (Exception e2) {
                return defaultValue;
            }
        }
    }

    /**
     * 
     * 此方法描述的是:根据key取BigDecial
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @param defaultValue
     *            默认值
     * @return BigDecimal
     */
    public static BigDecimal getBigDecimal(Map<String, Object> map, String key, BigDecimal defaultValue) {
        return new BigDecimal(getDouble(map, key, defaultValue.doubleValue()));
    }

    /**
     * 
     * 此方法描述的是:根据key取BigDecial
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return BigDecimal
     */
    public static BigDecimal getBigDecimal(Map<String, Object> map, String key) {
        return new BigDecimal(getDouble(map, key));
    }

    /**
     * 
     * 此方法描述的是:根据key取值int
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return int
     */
    public static int getInt(Map<String, Object> map, String key) {
        return JsonUtil.getInt(map, key, 0);
    }

    /**
     * 
     * 此方法描述的是:根据key取得boolean值
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @param defaultValue
     *            默认值
     * @return boolean
     */
    public static boolean getBoolean(Map<String, Object> map, String key, boolean defaultValue) {
        try {
            return (Boolean) map.get(key);
        }
        catch (Exception e) {
            try {
                return Boolean.parseBoolean(JsonUtil.toString(map.get(key)));
            }
            catch (Exception e2) {
                return defaultValue;
            }
        }
    }

    /**
     * 
     * 此方法描述的是:根据key取得boolean值,默认为false
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return boolean
     */
    public static boolean getBoolean(Map<String, Object> map, String key) {
        return getBoolean(map, key, false);
    }

    /**
     * 
     * 此方法描述的是:向obj数组中加新元素,
     * 
     * @param list
     *            list
     * @param obj
     *            增加的元素
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @SuppressWarnings("unchecked")
    public static void add(List<HashMap<String, Object>> list, Object obj) throws JsonParseException,
            JsonMappingException, IOException {
        list.add(JsonUtil.toBean(list, HashMap.class));
    }

    /**
     * 
     * 此方法描述的是:根据key取得double值
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @param defaultValue
     *            默认值
     * @return double
     */
    public static double getDouble(Map<String, Object> map, String key, double defaultValue) {
        try {
            return (Double) map.get(key);
        }
        catch (Exception e) {
            try {
                return Double.parseDouble(JsonUtil.toString(map.get(key)));
            }
            catch (Exception e2) {
                return defaultValue;
            }
        }

    }

    /**
     * 
     * 此方法描述的是:根据key取得double值
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return double
     */
    public static double getDouble(Map<String, Object> map, String key) {
        return getDouble(map, key, 0D);
    }

    /**
     * 
     * 此方法描述的是:根据key取得double值
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @param defaultValue
     *            默认值
     * @return long
     */
    public static long getLong(Map<String, Object> map, String key, long defaultValue) {
        try {
            return (Long) map.get(key);
        }
        catch (Exception e) {
            try {
                return Long.parseLong(JsonUtil.toString(map.get(key)));
            }
            catch (Exception e2) {
                return defaultValue;
            }
        }
    }

    /**
     * 
     * 此方法描述的是:根据key取得double值
     * 
     * @param map
     *            欲取值的map
     * @param key
     *            key
     * @return long
     */
    public static long getLong(Map<String, Object> map, String key) {
        return getLong(map, key, 0L);
    }

    /**
     * 
     * 此方法描述的是:将Object转化为Json格式字符串
     * 
     * @param obj
     *            欲转换的对象
     * @return String
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonGenerationException
     */
    public static String toString(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
        if (obj instanceof String) {
            return (String) obj;
        }
        else if (null == obj) {
            return null;
        }
        return JsonFormatter.toJsonString(obj);
    }

    /**
     * 
     * 此方法描述的是:将Object转化为Json格式字符串
     * 
     * @param obj
     *            欲转换的对象
     * @param dateFormat
     *            日期format
     * @return String
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonGenerationException
     */
    public static String toString(Object obj, DateFormat dateFormat) throws JsonGenerationException,
            JsonMappingException, IOException {
        if (obj instanceof String) {
            return (String) obj;
        }
        else if (null == obj) {
            return null;
        }
        JsonFormatter.setDateFormat(dateFormat);
        return JsonFormatter.toJsonString(obj);
    }

    /**
     * 
     * 此方法描述的是:将传入的对象转换成指定的对象
     * 
     * @param <T>
     *            模板类
     * @param cls
     *            与转化的类
     * @param obj
     *            被转换的对象
     * @return T
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    public static <T> T toBean(Object obj, Class<T> cls) throws JsonParseException, JsonMappingException, IOException {
        if (null == obj) {
            return null;
        }
        return JsonFormatter.toObject(JsonUtil.toString(obj), cls);
    }

    /**
     * 
     * 此方法描述的是:字符串转换为List<map>
     * 
     * @param obj
     *            与转换的对象
     * @return List<Map<String, Object>>
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @SuppressWarnings("unchecked")
    public static List<Map<String, Object>> toList(Object obj) throws JsonParseException, JsonMappingException,
            IOException {
        List<Map<String, Object>> lists = new LinkedList<Map<String, Object>>();
        List<Object> list = JsonUtil.toBean(obj, List.class);
        if (null != list) {
            for (Object object : list) {
                Map<String, Object> map = JsonUtil.toBean(object, HashMap.class);
                if (null != map) {
                    lists.add(map);
                }
            }
        }
        return lists;
    }

    /**
     * 
     * 此方法描述的是:字符串转换为List
     * 
     * @param <T>
     *            模板类
     * @param cls
     *            与转化的类
     * @param obj
     *            被转换的对象
     * @return T
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     * 
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> toList(Object obj, Class<T> cls) throws JsonParseException, JsonMappingException,
            IOException {
        List<T> lists = new LinkedList<T>();
        List<Object> list = JsonUtil.toBean(obj, List.class);
        if (null != list) {
            for (Object object : list) {
                T t = JsonUtil.toBean(object, cls);
                if (null != t) {
                    lists.add(t);
                }
            }
        }
        return lists;
    }

}

 

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class JsonFormatter {

    private static final ThreadLocal<ObjectMapper> INCLUDE_NULL_MAPPER     = new ThreadLocal();

    private static final ThreadLocal<ObjectMapper> NOT_INCLUDE_NULL_MAPPER = new ThreadLocal();

    private static ObjectMapper getMapper(boolean serializeNull) {
        ThreadLocal tl = serializeNull ? INCLUDE_NULL_MAPPER : NOT_INCLUDE_NULL_MAPPER;
        if (null == tl.get()) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.disable(new DeserializationConfig.Feature[] { DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES });

            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
            if (!serializeNull) {
                mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
                mapper.disable(new SerializationConfig.Feature[] { SerializationConfig.Feature.WRITE_NULL_MAP_VALUES });
            }

            tl.set(mapper);
        }

        return (ObjectMapper) tl.get();
    }

    public static String toJsonString(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
        return toJsonString(obj, true);
    }

    public static String toJsonAsString(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
        return toJsonAsString(obj, true);
    }

    public static byte[] toJsonAsBytes(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
        return toJsonAsBytes(obj, true);
    }

    public static void toJsonToFile(File file, Object obj) throws JsonGenerationException, JsonMappingException,
            IOException {
        toJsonToFile(file, obj, true);
    }

    public static void toJsonToOutputStream(OutputStream out, Object obj) throws JsonGenerationException,
            JsonMappingException, IOException {
        toJsonToOutputStream(out, obj, true);
    }

    public static void toJsonToWriter(Writer writer, Object obj) throws JsonGenerationException, JsonMappingException,
            IOException {
        toJsonToWriter(writer, obj, true);
    }

    public static <T> T toObject(String json, Class<T> clazz) throws JsonParseException, JsonMappingException,
            IOException {
        return toObject(json, clazz, true);
    }

    public static <T> T toObject(byte[] src, Class<T> clazz) throws JsonParseException, JsonMappingException,
            IOException {
        return toObject(src, clazz, true);
    }

    public static <T> T toObject(File file, Class<T> clazz) throws JsonParseException, JsonMappingException,
            IOException {
        return toObject(file, clazz, true);
    }

    public static <T> T toObject(InputStream input, Class<T> clazz) throws JsonParseException, JsonMappingException,
            IOException {
        return toObject(input, clazz, true);
    }

    public static <T> T toObject(Reader reader, Class<T> clazz) throws JsonParseException, JsonMappingException,
            IOException {
        return toObject(reader, clazz, true);
    }

    public static <T> T toObject(URL url, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        return toObject(url, clazz, true);
    }

    public static String toJsonString(Object obj, boolean serializeNull) throws JsonGenerationException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).writeValueAsString(obj);
    }

    public static String toJsonAsString(Object obj, boolean serializeNull) throws JsonGenerationException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).writeValueAsString(obj);
    }

    public static byte[] toJsonAsBytes(Object obj, boolean serializeNull) throws JsonGenerationException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).writeValueAsBytes(obj);
    }

    public static void toJsonToFile(File file, Object obj, boolean serializeNull) throws JsonGenerationException,
            JsonMappingException, IOException {
        getMapper(serializeNull).writeValue(file, obj);
    }

    public static void toJsonToOutputStream(OutputStream out, Object obj, boolean serializeNull)
            throws JsonGenerationException, JsonMappingException, IOException {
        getMapper(serializeNull).writeValue(out, obj);
    }

    public static void toJsonToWriter(Writer writer, Object obj, boolean serializeNull) throws JsonGenerationException,
            JsonMappingException, IOException {
        getMapper(serializeNull).writeValue(writer, obj);
    }

    public static <T> T toObject(String json, Class<T> clazz, boolean serializeNull) throws JsonParseException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).readValue(json, clazz);
    }

    public static <T> T toObject(byte[] src, Class<T> clazz, boolean serializeNull) throws JsonParseException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).readValue(src, clazz);
    }

    public static <T> T toObject(File file, Class<T> clazz, boolean serializeNull) throws JsonParseException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).readValue(file, clazz);
    }

    public static <T> T toObject(InputStream input, Class<T> clazz, boolean serializeNull) throws JsonParseException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).readValue(input, clazz);
    }

    public static <T> T toObject(Reader reader, Class<T> clazz, boolean serializeNull) throws JsonParseException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).readValue(reader, clazz);
    }

    public static <T> T toObject(URL url, Class<T> clazz, boolean serializeNull) throws JsonParseException,
            JsonMappingException, IOException {
        return getMapper(serializeNull).readValue(url, clazz);
    }

    public static void setDateFormat(DateFormat dateFormat) {
        getMapper(true).setDateFormat(dateFormat);
        getMapper(false).setDateFormat(dateFormat);
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics