简体   繁体   中英

Efficient way of Searching in JSON Object in java

I have a list of JSON Objects as: [{"name":"abc","id":"123"},{"name":"xyz","id":"345"}..] and a set of parameters like {"abc","def","xyz"}. I want to check whether the second set of parameters contains value that are not in name field of JSON Object in first array.

The algorithm I followed is:

Boolean flag = false;
   for{name : nameSet} {
     if(jsonObject.get("name")!=name{
       flag = true;
     }
   }

   if(flag){
     System.out.print("not matched");
   }

Are there any efficient way of doing it? Please suggest?

You are not checking each element with every element of Json array. You'll be needing an additional for loop for same.

Edit : Added the Json data to a key data . Refer the String json .

   Boolean found = false, flag = false;
   String json = "{ \"data\": [{"name":"abc","id":"123"},{"name":"xyz","id":"345"}]}"
   JSONObject object = new JSONObject(json);
   JSONObject getData = object.getJSONArray("data");

   for{name : nameSet} {
     found = false;
     for(int i = 0; i < getData.size(); i++) {
        JSONObject jsonObject = getData.getJSONObject(i);
        if(jsonObject.get("name").equals(name)){
          found= true;
          break;
        }
     }
     if(!found){
         flag = true;
         break;
     }
   }

   if(flag){
     System.out.print("not matched");
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM