Jayway JsonPath过滤json以获得不同的值

时间:2017-06-19 09:54:34

标签: json jsonpath

你知道是否有一个过滤函数可以从Jayson 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重复两次)。

由于

2 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分:0)

您可以使用.distinct()之类的方式:

Arrays.stream(JsonPath
   .parse(jsonString)
   .read(jsonPath, String[].class))
   .distinct()
   .collect(Collectors.toList())
   ;