009.使用Jackson讲JSON格式字符串转LIST写法

Jackson处理一般的JavaBean和Json之间的转换只要使用ObjectMapper 对象的readValue和writeValueAsString两个方法就能实现。但是如果要转换复杂类型Collection如 List<YourBean>,那么就需要先反序列化复杂类型 为泛型的Collection Type。

  • 如果是ArrayList<YourBean>那么使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);
  • 如果是HashMap<String,YourBean>那么 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);
public final ObjectMapper mapper = new ObjectMapper(); 
     
    public static void main(String[] args) throws Exception{  
        JavaType javaType = getCollectionType(ArrayList.class, YourBean.class); 
        List<YourBean> lst =  (List<YourBean>)mapper.readValue(jsonString, javaType); 
    }   
       /**   
        * 获取泛型的Collection Type  
        * @param collectionClass 泛型的Collection   
        * @param elementClasses 元素类   
        * @return JavaType Java类型   
        * @since 1.0   
        */   
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
    }

我的代码测试如下:

public class Object2JSON互转 {

    public static void main( String[] args ) throws IOException {

        Student student = new Student();
        student.setAccount("wukong");
        student.setUserName("悟空");
        //Jaskson工具类
        ObjectMapper objectMapper = new ObjectMapper();

        // 1.将Java对象转换为JSON格式的字符串
        String jsonStr = objectMapper.writeValueAsString(student);
        System.out.println("Student转JSON格式字符串:"+jsonStr);

        //2.将JSON格式的字符串转换Java对象
        Student shxt = objectMapper.readValue(jsonStr, Student.class);
        System.out.println("JSON格式字符串转Student对象:"+shxt);

        System.out.println("==============================================");
        List<Student> studentList = new ArrayList<Student>();
        studentList.add(student);

        student = new Student();
        student.setAccount("bajie");
        student.setUserName("八戒");
        studentList.add(student);
        jsonStr = objectMapper.writeValueAsString(studentList);
        System.out.println("StudentList转JSON格式字符串:"+jsonStr);

        JavaType t  = objectMapper.getTypeFactory().constructParametricType(List.class, Student.class);
        List<Student> shxtList = objectMapper.readValue(jsonStr, t);
        System.out.println("JSON格式字符串转shxtList集合:"+shxtList);

        List<Map<String,Object>> mapList = objectMapper.readValue(jsonStr, List.class);
        System.out.println("JSON格式字符串转mapList集合:"+mapList);
    }

}

简单封装工具类,在Java Web阶段也许用到

public class JsonUtil {

    /**
     * 将对象转换为json字符串
     * 
     * @param obj
     * @return
     * @throws Exception
     */
    public static String obj2string(Object obj) {
        StringWriter sw = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.writeValue(sw, obj);
        } catch (Exception e) {
        }
        return sw.toString();
    }

    /**
     * 将字符串转list对象
     * 
     * @param <T>
     * @param jsonStr
     * @param cls
     * @return
     */
    public static <T> List<T> str2list(String jsonStr, Class<T> cls) {
        ObjectMapper mapper = new ObjectMapper();
        List<T> objList = null;
        try {
            JavaType t = mapper.getTypeFactory().constructParametricType(
                    List.class, cls);
            objList = mapper.readValue(jsonStr, t);
        } catch (Exception e) {
        }
        return objList;
    }

    /**
     * 将字符串转为对象
     * 
     * @param <T>
     * @param jsonStr
     * @param cls
     * @return
     */
    public static <T> T str2obj(String jsonStr, Class<T> cls) {
        ObjectMapper mapper = new ObjectMapper();
        T obj = null;
        try {
            obj = mapper.readValue(jsonStr, cls);
        } catch (Exception e) {
        }
        return obj;
    }
    
    /**
     * 将字符串转为Page对象
     * 
     * @param <T>
     * @param jsonStr
     * @param cls
     * @return
     */
    public static <T> Page<T> str2page(String jsonStr, Class<T> cls) {
        ObjectMapper mapper = new ObjectMapper();
        Page<T> objList = null;
        try {
            JavaType t = mapper.getTypeFactory().constructParametricType(
                    Page.class, cls);
            objList = mapper.readValue(jsonStr, t);
        } catch (Exception e) {
        }
        return objList;
    }
    
    /**
     * 将字符串转为json节点
     * @param jsonStr
     * @return
     */
    public static JsonNode str2node(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readTree(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,742评论 18 399
  • 小编费力收集:给你想要的面试集合 1.C++或Java中的异常处理机制的简单原理和应用。 当JAVA程序违反了JA...
    八爷君阅读 4,650评论 1 114
  • Jackson使用规范以及代码示例 依赖包 Maven依赖: org.codehaus.jackson jacks...
    山石水寿阅读 4,731评论 0 3
  • 1 在了解“假性亲密关系”之前,我一直想不明白Nana和左先生分手的原因。我和左先生接触不多,但因为他是Nana的...
    小胸喵阅读 380评论 5 1
  • 八月二十二日 天气雨转晴 顺顺开学了,长达两个半月的暑期生活,今天正式结束了 全家人...
    盼之阅读 364评论 0 0