[英]JAVA: is the recursive approache the best way to check if json contains a specific key with a specific data value?
我想測試我的json輸入是否包含具有特定值的特定鍵。 我使用org.joson lib進行了解析和測試。 我遵循了遞歸方法。 這是最好的使用方法嗎? 還是有一個更簡單的?
public boolean isJsonContains(String dataKey, String dataValue) {
logger.systemWriteOutput("is JSON data key "+ dataKey + " contains value: " +dataValue,3);
JSONObject jsonObject = null;
if (jsonInput!=null){
jsonObject = new JSONObject(jsonInput);
return isJSONObjectContainsKeyAndValue(dataKey, dataValue,jsonObject );
}
else{
return false;
}
}
private boolean isJSONObjectContainsKeyAndValue (String dataKey, String dataValue, JSONObject object){
String[] keys = JSONObject.getNames(object);
logger.systemWriteOutput("JSONObject is: "+object.toString(),3);
for (String key : keys)
{
boolean result = isJSONKeyContainsValue(key, dataValue, object);
if(result)
return true;
}
logger.systemWriteOutput("no value : "+ dataValue +" has been found for id: " +dataKey,3);
return false;
}
private boolean isJSONKeyContainsValue (String dataKey, String dataValue, JSONObject object){
Object value = object.get(dataKey);
if(dataKey.equals(dataKey) && value.toString().equals(dataValue)){
logger.systemWriteOutput("value of id: " +dataKey+" is: "+value.toString(),3);
return true;
}
else{
logger.systemWriteOutput("value of id: " +dataKey+" is: "+value.toString(),3);
//see if that the nested element contains the id
if (value instanceof JSONArray){
logger.systemWriteOutput("key array is: "+dataKey,3);
JSONArray jsonArray = (JSONArray) object.getJSONArray(dataKey);
logger.systemWriteOutput("key array lenbgth is: "+jsonArray.length(),3);
return isJSONArrayContainsKeyAndValue(dataKey,dataValue, jsonArray);
}
else if (value instanceof JSONObject){
return isJSONObjectContainsKeyAndValue(dataKey, dataValue, object.getJSONObject(dataKey));
}
}
return false;
}
private boolean isJSONArrayContainsKeyAndValue(String dataKey, String dataValue, JSONArray jsonArray) {
boolean result;
logger.systemWriteOutput("jsonArray is: "+jsonArray.toString(),3);
logger.systemWriteOutput("jsonArray length is: "+jsonArray.length(),3);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
result= isJSONObjectContainsKeyAndValue(dataKey, dataValue ,jsonobject);
if( result)
return result;
}
return false;
}
在此先感謝您的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.