count members with jsonpath?

前端 未结 5 1085
生来不讨喜
生来不讨喜 2020-12-22 20:42

Is it possible to count the number of members using JsonPath?

Using spring mvc test I\'m testing a controller that generates

{\"foo\": \"oof\", \"ba         


        
5条回答
  •  旧时难觅i
    2020-12-22 21:33

    We can use JsonPath functions like size() or length(), like this:

    @Test
    public void givenJson_whenGetLengthWithJsonPath_thenGetLength() {
        String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
    
        int length = JsonPath
            .parse(jsonString)
            .read("$.length()");
    
        assertThat(length).isEqualTo(3);
    }
    

    Or simply parsing to net.minidev.json.JSONObject and get the size:

    @Test
    public void givenJson_whenParseObject_thenGetSize() {
        String jsonString = "{'username':'jhon.user','email':'jhon@company.com','age':'28'}";
    
        JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
    
        assertThat(jsonObject)
            .size()
            .isEqualTo(3);
    }
    

    Indeed, the second approach looks to perform better than the first one. I made a JMH performance test and I get the following results:

    | Benchmark                                       | Mode  | Cnt | Score       | Error        | Units |
    |-------------------------------------------------|-------|-----|-------------|--------------|-------|
    | JsonPathBenchmark.benchmarkJSONObjectParse      | thrpt | 5   | 3241471.044 | ±1718855.506 | ops/s |
    | JsonPathBenchmark.benchmarkJsonPathObjectLength | thrpt | 5   | 1680492.243 | ±132492.697  | ops/s |
    

    The example code can be found here.

提交回复
热议问题