Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally getting json data using java

Tags:

java

json

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



}
}}
like image 585
codehacker Avatar asked Nov 21 '16 07:11

codehacker


People also ask

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

How do you condition a JSON file?

Use the JSON_EXISTS condition to test whether a specified JSON value exists in JSON data. This condition returns TRUE if the JSON value exists and FALSE if the JSON value does not exist. Use this clause to specify the JSON data to be evaluated. For expr , specify an expression that evaluates to a text literal.

Can we use if condition in JSON?

Validating the JSON Schema Draft-07, JSON now supports the if...then...else keywords for conditional data representation.

How extract JSON data from string in Java?

JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser. parse(yourString); String msgType = (String) jsonObject. get("MsgType");


1 Answers

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"));
    }
like image 140
Alexander S Avatar answered Oct 25 '22 09:10

Alexander S