美文网首页
使用jackson转对象

使用jackson转对象

作者: 风一样的存在 | 来源:发表于2019-02-15 15:06 被阅读0次
把json字符串转化为嵌套对象
/**
*多个对象之间依赖关系,并且多个类都写在一个类里面,内部类必须使用static修饰
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FBLoginInfo {
    @JsonProperty(value = "active_sessions")
    private List<LoginInfo> activeSessions;

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    static class LoginInfo{
        private String location;
        private String app;
        private String device;

        @JsonProperty(value = "ip_address")
        private String ip;

        @JsonProperty(value = "created_timestamp")
        private Long createdTimestamp;
    }

}
把json字符串转化为对象数组
public class FileParseUtil {
    private final static ObjectMapper mapper = new ObjectMapper();

    public static List parse(String jsonStr, Class T){
        try{
            JavaType javaType = getCollectionType(ArrayList.class,T);
            List configList =  mapper.readValue(jsonStr, javaType);
            return configList;
        }catch (Exception e){
            log.error("解析文件错误");
        }
        return null;
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

}

相关文章

网友评论

      本文标题:使用jackson转对象

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