Search code examples
javajsonjsonpathjson-path-expression

JsonPath selecting object field if multiple condition matches


{
    "userName": "test"
    "customer": {
        "mode": "BANK",
        "modeDetails": {
            "accountNo": "12345678901001",
            "walletId": "11324354@paypal"
        }
    }
}

I am using jsonpath to select accountNo if mode="BANK" or else if mode=WALLET then walletId should be selected. I tried expression $.customer.modeDetails[$.customer.mode=='BANK'].accountNo but it doesn't work. Please help me on this.


Solution

  • public static void main(String[] args)  {   
        String jsonString = "{\r\n" + 
                "    \"userName\": \"test\",\r\n" + 
                "    \"customer\": {\r\n" + 
                "        \"mode\": \"BANK\",\r\n" + 
                "        \"modeDetails\": {\r\n" + 
                "            \"accountNo\": \"12345678901001\",\r\n" + 
                "            \"walletId\": \"11324354@paypal\"\r\n" + 
                "        }\r\n" + 
                "    }\r\n" + 
                "}";
        DocumentContext docCtx = JsonPath.parse(jsonString);
        JsonPath jsonPath = JsonPath.compile("$..[?(@.customer.mode==\"BANK\")].customer.modeDetails.accountNo");
        List<String> accounts = docCtx.read(jsonPath);
        System.out.println(accounts);
    }
    

    result

    ["12345678901001"]