- 需求:接收xml或者json,從中擷取指定字段的值,該值可能為value、jsonArray數組、jsonObject。
- 分析:同一采用對json進行查找的方式,如果接收的是xml則将xml轉換為json進行操作。
xml轉json
其中用到
json-java
包
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
擷取指定字段的值
/**
* 檢查json類型
* @param json json對象
* @return 1:jsonObject 2:jsonArray 3:值value
*/
public static int checkType(String json){
try {
JSONObject object = new JSONObject(json);
return ;
} catch (JSONException e) {
try {
JSONArray array = new JSONArray(json);
return ;
} catch (JSONException e1) {
return ;
}
}
}
/**
* 擷取目标值
* @param xmlJSONObj json對象
* @param goalKey 要查找的值
* @return
*/
private Object getGoalValue(JSONObject xmlJSONObj, String goalKey) {
JSONObject json = xmlJSONObj;
Object goalValue = null;
if (json.has(goalKey)) {
return json.get(goalKey);
} else {
Iterator ite = json.keys();
int i;
List<String> list = new ArrayList<String>();
while (ite.hasNext()) {
String k = (String) ite.next();
i = checkType(json.get(k).toString());
if ( == i) {
JSONObject jsonObj = json.getJSONObject(k);
goalValue = getGoalValue(jsonObj,goalKey);
} else if ( == i) {
JSONArray jsonArr = json.getJSONArray(k);
Iterator itArr = jsonArr.iterator();
while (itArr.hasNext()) {
JSONObject job = (JSONObject) itArr.next();
goalValue = getGoalValue(job,goalKey);
//①考慮目标結果要取一個json數組下不同對象的值
if (null != goalValue) {
list.add(goalValue.toString());
}
//②不考慮目标結果要多個值的情況(用①代碼則注釋②代碼,反之)
/*if (null != goalValue) {
break;
}*/
}
//①考慮目标結果要取一個json數組下不同對象的值
goalValue = list.toString().substring(, list.toString().length()-);
}
}
}
return goalValue;
}
public static void main(String[] args) {
Xml2JsonUtil xml = new Xml2JsonUtil();
//擷取xml
try {
Document doc = new SAXReader().read(new File("e:/demo.xml"));
String str = doc.asXML();
JSONObject xmlJSONObj = XML.toJSONObject(str);
//設定縮進
String json = xmlJSONObj.toString();
//輸出格式化後的json
System.out.println(json);
//目标值key
String goalKey = "code";
Object goalValue = xml.getGoalValue(xmlJSONObj,goalKey);
System.out.println("目标值是:" + goalValue);
} catch (DocumentException e) {
e.printStackTrace();
}
}