While Using JSON Array for adding Details the required filter parameter in the Array may appear in any part of the Array.To Filter the Array which has many multiple data types i.e String, Integer, boolean you need to do instanceof comparison

In the below JSON array has a List of Employee Details from which Employee from a Particular location is taken out after Filtering

 
 package com.mugil.json;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;

public class Employee {

	public static void main(String[] args) {
		String Location = "Chennai";
		JSONArray arrEmpDetails = getEmpList();

		System.out
				.println("*-----------------Before Filter-----------------------------*");
		displayEmpDetails(arrEmpDetails);
		arrEmpDetails = filterEmpByLocation(arrEmpDetails, Location);

		System.out
				.println("*-----------------After Filter-----------------------------*");
		displayEmpDetails(arrEmpDetails);
		System.out
				.println("*-----------------------------------------------------*");

	}

	private static void displayEmpDetails(JSONArray arrEmpDetails) {
		JSONArray arrEmpDet = new JSONArray();

		for (int i = 0; i < arrEmpDetails.length(); i++) {
			try {
				arrEmpDet = arrEmpDetails.getJSONArray(i);
				System.out.println(arrEmpDet);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	private static JSONArray filterEmpByLocation(JSONArray arrEmpDetails,
			String location) {
		JSONArray arrEmpByLoc = new JSONArray();
		String strToComp = null;
		boolean isSameLoc = false;

		for (int i = 0; i < arrEmpDetails.length(); i++) {
			try {
				JSONArray type = arrEmpDetails.getJSONArray(i);

				for (int j = 0; j < type.length(); j++) {
					Object strString = type.get(j);
					if (strString instanceof java.lang.String) {
						strToComp = (String) strString;
						isSameLoc = strToComp.equals(location);
					}
				}

				if (isSameLoc) {
					arrEmpByLoc.put(type);
					isSameLoc = false;
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return arrEmpByLoc;
	}

	public static JSONArray getEmpList() {
		JSONArray arrEmpDetails = new JSONArray();
		JSONArray arrPerDetails = new JSONArray();

		arrPerDetails.put("Empl1");
		arrPerDetails.put(23);
		arrPerDetails.put("Address1");
		arrPerDetails.put("Chennai");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl2");
		arrPerDetails.put(23);
		arrPerDetails.put("Address2");
		arrPerDetails.put("Coimbatore");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl3");
		arrPerDetails.put(24);
		arrPerDetails.put("Address3");
		arrPerDetails.put("Tirchy");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl4");
		arrPerDetails.put(26);
		arrPerDetails.put("Address4");
		arrPerDetails.put("Chennai");
		arrEmpDetails.put(arrPerDetails);

		return arrEmpDetails;
	}

}

Comments are closed.