Jayway JsonPath过滤JSON以获取唯一值

3

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

谢谢

2个回答

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

你可以像这样使用.distinct()

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接