用于json解析和迭代的API:
- org.json.simple
- org.json
我正在尝试从 ArchiveBatchChangeRequest -> DocumentSets -> QuerySpecification 下的 FieldName 中获取两个值,并将其作为 ArrayList 返回。
- elementNode = "ArchiveBatchChangeRequest;DocumentSets;QuerySpecification"
- objectValue = "字段名"
- batchFile = JSON 输入文件
所以返回值应该包含 CustomerName 和 DateCreated 因为 QuerySpecification 是一个大小为 2 的数组
我似乎无法让这个工作。恐怕我最初的遍历点很糟糕,或者可以更容易地完成。
JSON 输入文件:
{
"ArchiveBatchChangeRequest": [{
"BatchRunSpecification": [{
"BatchOperation": "EXTRACT"
}]
},
{
"OutputSpecification": [{
"ReportFieldNames": ["ReportField1"]
}]
},
{
"DocumentSets": [{
"DocumentSetNo": "1",
"QuerySpecification": [{
"FieldName": "CustomerName",
"SimpleQuery": [{
"Operator": "EQUAL",
"Values": ["Customer1"]
}]
},
{
"FieldName": "DateCreated",
"SimpleQuery": [{
"Operator": "EQUAL",
"Values": ["19-12-2015"]
}]
}]
}]
}]
}
编码:
public ArrayList<String> getElementValue(String elementNode, String objectValue, File batchFile) throws IOException, ParseException{
String [] elementArray = elementNode.split(";");
JSONObject outerObject = null;
ArrayList<String> values = new ArrayList<String>();
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(new FileReader(batchFile));
outerObject = new JSONObject(object.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray getArray = null;
for (int i = 0; i < elementArray.length; i++) {
getArray = outerObject.getJSONArray(elementArray[i]);
for (int j = 0; j < getArray.length(); j++) {
for (int j2 = 0; j2 < elementArray.length; j2++) {
if(getArray.getJSONObject(j).names().get(0).equals(elementArray[j2])){
outerObject = getArray.getJSONObject(j);
}
}
}
if(i == elementArray.length - 1){
outerObject = getArray.getJSONObject(0);
}
}
try{
getArray = null;
getArray = outerObject.getJSONArray(objectValue);
}catch(JSONException je){ //Object is not an JSONArray
je.printStackTrace();
}finally{
if(getArray != null){
for (int i = 0; i < getArray.length(); i++) {
values.add(getArray.getString(i).replace("\"", ""));
}
}else
values.add(outerObject.getString(objectValue));
}
return values;
}