2017-06-19 8 views
1

Wissen Sie, ob es eine Filterfunktion gibt, die mir eindeutige (distinct) Werte aus einer JSON-Datei mit Jayway JsonPath bekommt?Jayway JsonPath Filter json, um verschiedene Werte zu erhalten

Ich habe eine einfache json

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

und ich brauche alle unterschiedlichen Funktionen Werte für ThingA und ThingB zu bekommen. Vorerst I-Filter mit

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

aber das gibt mir die Werte 1,2,3,4,1,6 (so wird 1 zweimal wiederholt).

Dank

Antwort

1

Sie könnten vielleicht ein com.jayway.jsonpath.Predicate filtern für verschiedene Werte, wie folgt verwenden:

@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; 
     } 
    } 
} 
Verwandte Themen