I have a small function that takes in a list of JSON objects that has the format below. The function below that wants to see if the brand and model of car passed to it can be matched against the List parameter called jsonfiltersList
. The code I have works, but being somewhat new to coding and Java I wanted to know if I can optimize the code snippet to make it more compact somehow. Any thoughts?
{ auto_filters : [ { "brand" : "Toyota" }, { "brand" : "Honda", "models" : [ "Civic", "Accord" ] } ] }
And the code:
public static boolean filterMatch(String brand, String model, ArrayList<JSONObject> jsonFiltersList) { boolean brandMatch = false; boolean modelMatch = false; if ((jsonFiltersList == null) || (jsonFiltersList.size() < 1)) return true; try { for (JSONObject j : jsonFiltersList) { if (j.get("brand").equals(brand)) { brandMatch = true; } if (brandMatch) { JSONArray jArr = null; if (j.has("models")) { jArr = (JSONArray) j.get("models"); } ArrayList<String> modelsArr = new ArrayList<String>(); if (jArr != null) { for (int i = 0; i < jArr.length(); i++) modelsArr.add(jArr.get(i).toString()); if (modelsArr.contains(model)) { modelMatch = true; break; } } else { modelMatch = true; break; } } brandMatch = false; } } catch(Exception e) { e.printStackTrace(); } return brandMatch && modelMatch; }