Search code examples
javajsonpath

Criteria inside JsonPath


I'm trying to filter jsonPath by type. To extract Integers

I would expect this will return nothing as 'xx' is not integer:

JsonPath.read("{'status': 'xx'}", "$.status", Criteria.where(".status").is(Integer.class));

Similarly this

JsonPath.read("{'status': 'xx'}", "$.status", Criteria.where(".status").eq(200));

both cases returns String = "xx" I would expect it to return either null or empty string as it doesn't match number 200.


Solution

  • Correct @i.bondarenko, I would simply add - for the first check of searching whether status value is an Integer - that he/she should use a Pattern to pass to the filter, like for example

    Pattern numberPattern = Pattern.compile("\\d+");
    Filter filter = filter(where("status").regex(numberPattern));
    Object test = JsonPath.read("{\"status\": \"xx\"}", "$[?].status", filter);
    
    System.out.println("Test : " + test);
    

    That will print Test : []

    UPDATED

    It is a JSONArray indeed, therefore, you already have the Integers of your whole JSON in that array (if they exist). For example,

    Pattern numberPattern = Pattern.compile("\\d+");
    Filter filter = filter(where("status").regex(numberPattern));
    net.minidev.json.JSONArray test = JsonPath.read("{\"status\": 300}", "$[?].status", filter);
    
    if (!test.isEmpty()) {
        for (Object object : test) {
             System.out.println("Test : " + object.toString());
        }
    }
    

    So, there is no need to add try-catch, it is enough to just check the size of your JSONArray result