0

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.

Emiter
  • 268
  • 2
  • 13

2 Answers2

3

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

dZ.
  • 404
  • 1
  • 5
  • 9
  • thanks. Seem to work but as the output is JsonArray and stuff, I'd better do try { } catch (MappginException) in that case to determine if it is Integer. – Emiter Oct 18 '19 at 11:05
2

You should use $[?].status as json path for criteria. Also where("field").is("value") accept value but not a class. You could have a look at implementation of Criteria.eq(...)

public Criteria eq(Object o) {
    return is(o);
}

Here is the code:

public static void main(String[] args) {
    Criteria criteria = Criteria.where("status").gt(10);
    Object read = JsonPath.read("{'status': 18}", "$[?].status", criteria);
    System.out.println("First: " + read);
    read = JsonPath.read("{'status': 2}", "$[?].status", criteria);
    System.out.println("Second: " + read);

    criteria = Criteria.where("status").is("value");
    read = JsonPath.read("{'status': 'value'}", "$[?].status", criteria);
    System.out.println("Third: " + read);

    criteria = Criteria.where("status").is("value");
    read = JsonPath.read("{'status': 'NON'}", "$[?].status", criteria);
    System.out.println("Third: " + read);
}

Output:

First: [18]
Second: []
Third: ["value"]
Third: []
i.bondarenko
  • 3,442
  • 3
  • 11
  • 21