efthialex efthialex - 4 months ago 20
JSON Question

How to filter JSON String array based on attributes?

I have the following JSON-String array

[
{
"firstName": "Patrick",
"lastName": "Smith",
"loginName":"test0003@test.com",
"Country":"US",
"phoneNumber": "287 125-1434",
"status": "340"
},
{
"firstName": "Bob",
"lastName": "Williams",
"loginName":"test0002@test.com",
"Country":"US",
"phoneNumber": "213 111-9943",
"status": "215"
},
{
"firstName": "John",
"lastName": "Johnson",
"loginName":"test0001@test.com",
"Country":"DE",
"phoneNumber": "212 555-1234",
"status": "340"
},
{
"firstName": "John",
"lastName": "Johnson",
"loginName":"test0001@test.com",
"Country":"DE",
"phoneNumber": "212 555-1234",
"status": "215"
},
{
"firstName": "John",
"lastName": "Johnson",
"loginName":"test0001@test.com",
"Country":"DE",
"phoneNumber": "212 555-1234",
"status": "167"
},
{
"firstName": "George",
"lastName": "Jones",
"loginName":"test0004@test.com",
"Country":"FR",
"phoneNumber": "217 987-2634",
"status": "340"
}
]


and I need to return only this part

{
"firstName": "John",
"lastName": "Johnson",
"loginName":"test0001@test.com",
"Country":"DE",
"phoneNumber": "212 555-1234",
"status": "167"
}


by providing values for loginName and status

I need to create a method as the one below.

public String filterJsonArray(String array, String keyOne, Object valueOne, String keyTwo, Object valueTwo) throws ParseException {

}


Can someone give me an idea of how I could implement this.

Answer

Using Jackson, this is the crudest snippet I can think of:

private static ObjectMapper mapper = new ObjectMapper();

public static void main(String[] args) throws IOException {
    System.out.println(filterJsonArray(JSON, "loginName", "test0001@test.com", "status", "167"));
}

public static String filterJsonArray(String array, String keyOne, Object valueOne, String keyTwo, Object valueTwo) throws IOException {
    Map[] nodes = mapper.readValue(array, HashMap[].class);

    for (Map node : nodes) {
        if (node.containsKey(keyOne) && node.containsKey(keyTwo)) {
            if (node.get(keyOne).equals(valueOne) && node.get(keyTwo).equals(valueTwo)) {
                return mapper.writeValueAsString(node);
            }
        }
    }

    return null;
}

Of course it will only returns the first match to the given pairs. If you need all the values, make it return a list instead and populate it inside the loop.

Comments