Jackson将json字符串转换成泛型List/map

url: http://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html

 

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

 

 

GitHub 加速计划 / js / json
37
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:5 个月前 )
34665ae6 binary -> binary_t Signed-off-by: Robert Chisholm <robert.chisholm@sheffield.ac.uk> 20 天前
f3dc4684 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.9 to 3.28.10. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0...b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 27 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐