Java json转Map,转bean,转List

引用jackson/***json转Map,转bean,转Listbyhttp://blog网络
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码

引用jackson

/**
*  json转Map,转bean,转List<bean> by http://blog.csdn.net/21aspnet/
*  需要jackjson jar包
*/
public class JsonUtil {

    /**
     * Object转Json
     */
    public static String ObjectToJson(Object value) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String js = mapper.writeValueAsString(value);
            return js;
        } catch (Exception e) {
            System.out.println(e.toString());
            return "Error";
        }
    }

    /**
     * Json转Object
     */
    public static Object JsonToList(String json, Class<?> bean) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, bean);
        return mapper.readValue(json, javaType);
    }

    /**
     * Json转Object
     */
    public static Object JsonToBean(String json, Class<?> bean) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().uncheckedSimpleType(bean);
        return mapper.readValue(json, javaType);
    }

    /**
     * Json转Map
     */
    public static Map<String, Map<String, String>> JsonToMap(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Map<String, String>> maps = mapper.readValue(json, Map.class);                      
            return maps;
        } catch (Exception e) {
            System.out.println(e.toString());
            return null;
        }
    }
}

 

本文来源21aspnet,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/2108

发表评论