6

below is my code where Im trying to check id id =101 and getting the name= Pushkar assosiated with the id=101.But the code is not working as expected.

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"));
    }



}
}}
1
  • check your if condition if(ID1!=null && out1.equals(ID1)) here out1 and ID1 might have different values hence your condition will not true Commented Nov 21, 2016 at 7:47

2 Answers 2

1

why do you compare out1 with ID1? Either you want to check if out1 contains ID1 (which is not very meaningfull, as you retrieve ID1 from out1) or you want to verify that ID1 equals 101. In that case you would rather want to say something like:

if(ID1!=null && "101".equals(ID1))
    {
    System.out.println("NAME"+jobj.get("name"));
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Try to change if condition like this:

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

Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.