关于如何快速初始化Java的复杂集合对象问题
最快的方法就是手写Json格式的List<VO>,然后转成List<VO>对象
代码示例,如何快速初始化这个对象的List集合
public class State {
@Id
private Integer id;
@Column(name = "ch_name")
private String chName;
@Column(name = "en_name")
private String enName;
private String code;
private String capital;
private String capitalen;
private String remark;
}
对于这个List《VO》有这个数据
[
State(id=1, chName=E, enName=D, code=C, captial=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, captial=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, captial=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, captial=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, captial=B, capitalen=A, remark=F)
]
转成Json后
[
{"capitalen":"A","code":"C","enName":"D","remark":"F","id":1,"captial":"B","chName":"E"},
{"capitalen":"A","code":"C","enName":"D","remark":"F","id":1,"captial":"B","chName":"E"},
{"capitalen":"A","code":"C","enName":"D","remark":"F","id":1,"captial":"B","chName":"E"},
{"capitalen":"A","code":"C","enName":"D","remark":"F","id":1,"captial":"B","chName":"E"},
{"capitalen":"A","code":"C","enName":"D","remark":"F","id":1,"captial":"B","chName":"E"}
]
怎么实现呢?
我们可以方便初始化一个JsonArray对象,然后用工具类解析生成List<Vo>对象
List<State> states = JSONUtil.toList(new JSONArray("[" +
"{\"capitalen\":\"A\",\"code\":\"C\",\"enName\":\"D\",\"remark\":\"F\",\"id\":1,\"capital\":\"B\",\"chName\":\"E\"}," +
"{\"capitalen\":\"A\",\"code\":\"C\",\"enName\":\"D\",\"remark\":\"F\",\"id\":1,\"capital\":\"B\",\"chName\":\"E\"}," +
"{\"capitalen\":\"A\",\"code\":\"C\",\"enName\":\"D\",\"remark\":\"F\",\"id\":1,\"capital\":\"B\",\"chName\":\"E\"}," +
"{\"capitalen\":\"A\",\"code\":\"C\",\"enName\":\"D\",\"remark\":\"F\",\"id\":1,\"capital\":\"B\",\"chName\":\"E\"}," +
"{\"capitalen\":\"A\",\"code\":\"C\",\"enName\":\"D\",\"remark\":\"F\",\"id\":1,\"capital\":\"B\",\"chName\":\"E\"}" +
"]"), State.class);
[
State(id=1, chName=E, enName=D, code=C, capital=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, capital=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, capital=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, capital=B, capitalen=A, remark=F),
State(id=1, chName=E, enName=D, code=C, capital=B, capitalen=A, remark=F)
]