把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);
}
}
网友评论