Reputation: 795
I have a JSON file like below. I want to read all the values and check if the input string contains one of the JSON values, the return true. But with my try, always it returns 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;
}
Upvotes: 1
Views: 2150
Reputation: 7269
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 (e.g. word1
, en
, word2
...)
If you're looking for values of the word
field only, then try the following:
return mapper.readValue("", new TypeReference<Map<String, List<Map<String, String>>>>() {})
.values()
.stream()
.flatMap(List::stream)
.map(m -> m.get("word"))
.anyMatch(content::contains);
Upvotes: 1
Reputation: 59
for (Map.Entry<?, ?> entry : map.entrySet())
will get you a LinkedHashMap Entry. 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
Upvotes: 0