这是我的JSONArray结构
{
"docs": [
{
"_index": "junit",
"_type": "type",
"_id": "2003",
"_version": 1,
"found": true,
"_source": {
"data": "\"year\":\"2003\"",
"name": "2003",
"type": "year",
"ancestors": [
"PARTS"
],
"child": {
"year_make": [
{
"name": "Honda",
"id": "2003_Honda"
}
]
}
}
},
{
"_index": "junit",
"_type": "type",
"_id": "2003_Honda",
"_version": 1,
"found": true,
"_source": {
"data": "\"year\":\"2003\", \"make\":\"Honda\"",
"name": "2003_Honda",
"type": "year_make",
"ancestors": [],
"child": {}
}
}
]}
这是我想将响应转换为
的java对象public class PartsNode extends Node {
@Id
String id;
...
}
上面的类扩展了这个抽象类
public abstract class Node {
String name;
List<String> ancestors = new ArrayList<>();
String type;
Map <String, Set<ChildInfo>> child = new LinkedHashMap<>();
String data;
}
我正在尝试做这样的事情
private List<T> translateResponseToNodes(String responseBody, Class<T> classType) {
List<T> nodes = new ArrayList<T>();
if(StringUtils.isNotBlank(responseBody)) {
JSONObject responseJson = new JSONObject(responseBody);
JSONArray jsonArr = responseJson.getJSONArray("docs");
int length = jsonArr.length();
for(int i=0; i<length; i++){
JSONObject jObj = jsonArr.getJSONObject(i);
JsonElement data = (JsonElement) jObj.get("_source");
Gson gson = new Gson();
T node = gson.fromJson(data, classType);
node.setId(jObj.get("_id").toString());
nodes.add(node);
}
}
return nodes;
}
目前我正在使用输入classtype来确定Node的类型。假设应该有更好的方法来做到这一点。