美文网首页json程序员Java学习笔记
009.使用Jackson讲JSON格式字符串转LIST写法

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

作者: 胖先森 | 来源:发表于2017-07-21 15:54 被阅读3120次

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;
    }
}

相关文章

网友评论

    本文标题:009.使用Jackson讲JSON格式字符串转LIST写法

    本文链接:https://www.haomeiwen.com/subject/brsekxtx.html