2017-06-19 32 views
1

你知道是否有一個過濾器函數可以從JSON文件中獲得與Jayway JsonPath唯一(不同的)值嗎?Jayway JsonPath過濾JSON以獲取不同的值

我有一個簡單的JSON

{ "services": [ 
{ 
    "value": "ThingA", 
    "functions": [ 
    { 
     "value": "1" 
    }, 
    { 
     "value": "2" 
    }, 
    { 
     "value": "3" 
    } 
    ] 
}, 
{ 
    "value": "ThingB", 
    "functions": [ 
    { 
     "value": "4" 
    }, 
    { 
     "value": "1" 
    }, 
    { 
     "value": "6" 
    } 
    ] 
}]} 

,我需要得到所有ThingA和ThingB了不同的功能價值。 現在我

$.services[?(@.value in ['thingA','thingB'])].functions[*][*] 

篩選,但這是給我的價值觀1,2,3,4,1,6(1如此重複兩次)。

感謝

回答

1

也許你可以使用一個com.jayway.jsonpath.Predicate來過濾不同的值,如:

@Test 
public void canExtractDistinctValues() { 
    List<String> read = JsonPath.parse(... your json ...).read("$.services[?(@.value in ['ThingA','ThingB'])].functions[?].value", List.class, 
      new DistinctPredicate("value")); 

    assertThat(read.size(), is(5)); 
    assertThat(read, hasItem("1")); 
    assertThat(read, hasItem("2")); 
    assertThat(read, hasItem("3")); 
    assertThat(read, hasItem("4")); 
    assertThat(read, hasItem("6")); 
} 

private class DistinctPredicate implements Predicate { 
    private final String fieldName; 
    private final Set distinctValues; 

    public DistinctPredicate(String fieldName) { 
     this.fieldName = fieldName; 
     this.distinctValues = Sets.newHashSet(); 
    } 

    @Override 
    public boolean apply(Predicate.PredicateContext context) { 
     String value = context.item(Map.class).get(fieldName).toString(); 
     if (distinctValues.contains(value)) { 
      return false; 
     } else { 
      distinctValues.add(value); 
      return true; 
     } 
    } 
}