功能:用来判断复杂json数据中是否包含特定key。
方法:
private Boolean isContainKeyForJson(JSONObject json,String target,Boolean result) {
if(!result) {
for(String key :json.keySet()) {
if(target.equals(key)) {
return true;
}
Object temp = json.get(key);
if (temp instanceof JSONObject) {
JSONObject new_name = (JSONObject) temp;
result = isContainKeyForJson(new_name,target, false);
}
if(result) {
return result ;
}
}
}
return result ;
}
测试数据:
{"properties":{"user_utt":{"fielddata":"true","analyzer":"ngram_analyzer","term_vector":"yes","type":"text"},"user_utt_lemma_yomi":{"fielddata":"true","analyzer":"whitespace","term_vector":"yes","type":"text"},"ui_reserve2":{"index":"not_analyzed","type":"keyword","type1":"keyword"},"ui_reserve1":{"index":"not_analyzed","type":"keyword"},"add_utt":{"index":"not_analyzed","type":"keyword"},"topic":{"index":"not_analyzed","type":"keyword"},"current_status":{"index":"not_analyzed","type":"integer"},"original_user_utt":{"index":"not_analyzed","type":"keyword"},"user_utt_length":{"index":"not_analyzed","type":"long"},"user_utt_lemma":{"fielddata":"true","analyzer":"whitespace","term_vector":"yes","type":"text"},"subtopic":{"index":"not_analyzed","type":"keyword"}}}
测试方法:
@Test
public void test() throws IOException {
JSONObject test = JSONObject.parseObject(BusinessConstant.UI_MAPPING_JA);
System.out.println(isContainKeyForJson(test,"type1",false));
}
private Boolean isContainKeyForJson(JSONObject json,String target,Boolean result) {
if(!result) {
for(String key :json.keySet()) {
if(target.equals(key)) {
return true;
}
Object temp = json.get(key);
if (temp instanceof JSONObject) {
JSONObject new_name = (JSONObject) temp;
result = isContainKeyForJson(new_name,target, false);
}
if(result) {
return result ;
}
}
}
return result ;
}