• jackson-mapper使用工具类


    import com.google.common.collect.Lists;
    import org.codehaus.jackson.annotate.JsonMethod;
    import org.codehaus.jackson.map.DeserializationConfig;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.map.SerializationConfig;
    import org.codehaus.jackson.map.type.TypeFactory;
    import org.codehaus.jackson.type.JavaType;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    public class JSONUtil {

    private static Logger logger = LoggerFactory.getLogger(JSONUtil.class);

    private static ObjectMapper mapper = new ObjectMapper();

    static {
    mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);//所有的属性都可以访问到(从private 到public)
    mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);//缩紧的方式进行序列化输出
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);//反序列化时,属性如果没有set方法,不报错。

    /**
    * Object to JSON的转化
    *
    * @param obj
    * @return
    */
    public static String object2Json(Object obj) {
    try {
    return mapper.writeValueAsString(obj);
    } catch (IOException e) {
    logger.error("parse Object to String error", e);
    }

    return null;
    }

    /**
    * jsonArray转化成list
    */
    public static <T> List<T> jsonStr2List(String jsonStr, Class<?> clazz) {
    List<T> list = Lists.newArrayList();
    try {
    // 指定容器结构和类型(这里是ArrayList和clazz)
    TypeFactory t = TypeFactory.defaultInstance();
    list = mapper.readValue(jsonStr,
    t.constructCollectionType(ArrayList.class, clazz));
    } catch (IOException e) {
    logger.error("反序列化序列化报错", e);
    }
    return list;
    }

    public static <T> T readValue(String o, Class<T> clazz) {
    try {
    return mapper.readValue(o, clazz);
    } catch (IOException e) {
    logger.error("反序列化错误", e);
    }
    return null;
    }

    public static <T> T readJson(String jsonStr, Class<?> collectionClass,
    Class<?>... elementClasses) {
    ObjectMapper mapper = new ObjectMapper();

    JavaType javaType =
    mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);

    try {
    return mapper.readValue(jsonStr, javaType);
    } catch (IOException e) {
    e.printStackTrace();
    }
    return null;
    }

    public static ObjectMapper getMapper() {
    return mapper;
    }
    }

    参考资料:

    http://a52071453.iteye.com/blog/2175398

  • 相关阅读:
    Cognos无法解密来着内容库的用户名和密码凭证
    JavaScript 中的对象引用
    npm install出现的错误
    箭头函数中this的用法
    [译]ArcGIS Server Map Service Cache的组织结构
    [C#] 如何选择抽象基类与接口
    数据库设计规范
    在DataTable中查询应该注意的问题
    坦克大战总结
    仓库管理系统总结(1)
  • 原文地址:https://www.cnblogs.com/tom-plus/p/6163728.html
Copyright © 2020-2023  润新知