简体   繁体   English

如何过滤嵌套的 JSON 值?

[英]How to filter nested JSON values?

I have a JSON file like below.我有一个 JSON 文件,如下所示。 I want to read all the values and check if the input string contains one of the JSON values, the return true.我想读取所有值并检查输入字符串是否包含 JSON 值之一,返回 true。 But with my try, always it returns false .但是通过我的尝试,它总是返回false

{
  "RECORDS": [
    {
      "word": "word1",
      "language": "en"
    },
    {
      "word": "word2",
      "language": "en"
    },
    {
      "word": "word3",
      "language": "en"
    }
  ]
}

My method我的方法


 public static boolean check(String content) throws IOException {
        File file = ResourceUtils.getFile("classpath:sample.json");

        ObjectMapper mapper = new ObjectMapper();
        Map<?, ?> map = mapper.readValue(file, Map.class);
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            if (content.contains(entry.getValue().toString())) {
                return true;
            } else
                return false;
        }

        return false;
    }

Try this:尝试这个:

return mapper.readValue(file, new TypeReference<Map<String, List<Map<String, String>>>>() {})
             .values()
             .stream()
             .flatMap(List::stream)
             .map(Map::values)
             .flatMap(Collection::stream)
             .anyMatch(content::contains);

The code snippet above will check whether your content string contains any of the nested values (eg word1 , en , word2 ...)上面的代码片段将检查您的content字符串是否包含任何嵌套值(例如word1enword2 ...)


If you're looking for values of the word field only, then try the following:如果您只查找word字段的值,请尝试以下操作:

return mapper.readValue("", new TypeReference<Map<String, List<Map<String, String>>>>() {})
             .values()
             .stream()
             .flatMap(List::stream)
             .map(m -> m.get("word"))
             .anyMatch(content::contains);

for (Map.Entry<?, ?> entry: map.entrySet()) will get you a LinkedHashMap Entry. for (Map.Entry<?, ?> entry: map.entrySet())将为您提供一个 LinkedHashMap 条目。 So basically, your entry variable will look something like this:所以基本上,你的入口变量看起来像这样:

在此处输入图像描述

for your code to work, you will need to iterate over the values again before doing the contains check为了使您的代码正常工作,您需要在执行contains检查之前再次迭代这些值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM