要想解析这种复杂的字符串,首先得先定义好与之相符的java POJO 对象,经过观察,我们发现,这个是一个json对象数组,每一个对象里包含了许多属性,其中还有一个属性的类型也是对象数组。所有,我们从里到外,先定义最里面的对象:
public class Column {
private String key;
private String header;
private String width;
private String allowSort;
private String hidden;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
//这里省略部分getter与setter方法
}
再定义外层的对象:
import java.util.List;
import org.apache.commons.collections4.map.LinkedMap;
public class Query {
private String id;
private String key;
private String tableName;
private String className;
private List<LinkedMap<String, Object>> column;
private List<Column> columnList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
//这里省略部分getter与setter方法
public List<LinkedMap<String, Object>> getColumn() {
return column;
}
public void setColumn(List<LinkedMap<String, Object>> column) {
this.column = column;
}
public List<Column> getColumnList() {
return columnList;
}
public void setColumnList(List<Column> columnList) {
this.columnList = columnList;
}
}
我的这个json文件放置在类路径下,最后想将这个json字符串转化为List
/**
* 读取类路径下的配置文件
* 解析成对象数组并返回
* @throws IOException
*/
@Test
public List<Query> test() throws IOException {
// 读取类路径下的query.json文件
ClassLoader cl = this.getClass().getClassLoader();
InputStream inputStream = cl.getResourceAsStream("query.json");
String jsontext = IOUtils.toString(inputStream, "utf8");
// 先将字符jie串转为List数组
List<Query> queryList = JSON.parseArray(jsontext, Query.class);
for (Query query : queryList) {
List<Column> columnList = new ArrayList<Column>();
List<LinkedMap<String,Object>> columns = query.getColumn();
for (LinkedMap<String, Object> linkedMap : columns) {
//将map转化为java实体类
Column column = (Column)map2Object(linkedMap, Column.class);
System.out.println(column.toString());
columnList.add(column);
}
query.setColumnList(columnList); //为columnList属性赋值
}
return queryList;
}