0

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?

Venki WAR
  • 1,997
  • 4
  • 25
  • 38
usergs
  • 1,344
  • 3
  • 9
  • 18
  • What is the implementation of `jsonObject.get()`? – Cargeh May 11 '18 at 08:54
  • @Cargeh Didnt get what you are asking, can you explain – usergs May 11 '18 at 08:56
  • whether this could be optimized requires understanding of how `jsonObject.get()` works (the algorithm). If this is pseudo code, then the question is unlikely to be answered. If this is a library function, please provide the name of the library – Cargeh May 11 '18 at 08:58
  • @Cargeh I have used org.json.simple.JSONObject in java – usergs May 11 '18 at 09:03
  • First, you should start by comparing `String` correctly. `jsonObject.get("name")!=name` will not work. Then, simply break the iteration when you get flag at true. – AxelH May 11 '18 at 09:21
  • `JSONObject ` inside has `has(String name)` method. Isn't it enough? – dehasi May 11 '18 at 09:23
  • I would use JsonPath unless there was a measured issue with performance – Sami Korhonen May 11 '18 at 10:39

1 Answers1

0

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");
   }
Sandesh Gupta
  • 1,175
  • 2
  • 11
  • 19