Conditionally receiving json data using java

below is my code, where Im trying to check id id = 101 and get name = Pushkar associated with id = 101. But the code is not working properly.

import org.json.simple.JSONArray; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class A6 { public static void main(String[] args) throws ParseException, JSONException{ String out1="{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}"; //System.out.println(out1); JSONParser parser=new JSONParser(); JSONObject obj=(JSONObject)parser.parse(out1); //System.out.print(obj); JSONArray jarr=(JSONArray)obj.get("Employee"); //System.out.print(jarr); for (int i=0;i<jarr.size();i++) { JSONObject jobj=(JSONObject)jarr.get(i); String ID1=(String)jobj.get("id"); System.out.println(ID1); if(ID1!=null && out1.equals(ID1)) { System.out.println("NAME"+jobj.get("name")); } } }} 
+6
source share
2 answers

why do you compare out1 with ID1? Either you want to check if out1 contains ID1 (which is not very important, since you are extracting ID1 from out1), or you want to check that ID1 is 101. In this case, you would rather want to say something like:

 if(ID1!=null && "101".equals(ID1)) { System.out.println("NAME"+jobj.get("name")); } 
+1
source

Try changing this condition as follows:

 if(ID1!=null && out1.contains(ID1)) { System.out.println("NAME"+jobj.get("name")); } 

Thanks.

+1
source

Source: https://habr.com/ru/post/1012514/


All Articles