I have a JSON as follows .
[{
"empid": "1",
"name": "Mark"
},
{
"empid": "2",
"name": "Steve"
},
{
"empid": "1",
"name": "Luke "
}
]
Based on the empid as input , i need to get appropiate name
I have tried this its working .
But instead of looping is there any simple way ??
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONPArseEx {
public static void main(String[] args) throws JSONException {
String empIdInput = "2";
String jsonStr = "[{\r\n" +
" \"empid\": \"1\",\r\n" +
" \"name\": \"Mark\"\r\n" +
" \r\n" +
" },\r\n" +
" {\r\n" +
" \"empid\": \"2\",\r\n" +
" \"name\": \"Steve\"\r\n" +
" \r\n" +
" },\r\n" +
" {\r\n" +
" \"empid\": \"1\",\r\n" +
" \"name\": \"Luke \"\r\n" +
" \r\n" +
" }\r\n" +
"]";
JSONArray jsonarray = new JSONArray(jsonStr);
for(int i=0;i<jsonarray.length();i++)
{
JSONObject json_obj = jsonarray.getJSONObject(i);
if(json_obj.get("empid").equals(empIdInput))
{
System.out.println(json_obj.get("name"));
}
}
}
}
Output is
Steve
$.[?(@.empid==1)].nameis something that will do the same for you