在 Java 中搜索 JSON 中的字符串并返回一个子集作为 json

问题描述 投票:0回答:1

我正在开发 Java Spring Boot 应用程序。我有一个以下格式的 Json。我需要搜索字符串并以仅包含匹配条目的相同 json 格式返回结果。 原始json如下:

{
    "version": "1.0.2",

    "students": ["John Smith", "John Green", "Martin King"],

    "teachers": ["John Lord", "Martin Evans", "Steve John", "Gordon Lee", "Leo Martin"],

    "authors" : ["Martin Fowler", "Erich Gamma"]
}

例如,如果我搜索字符串“mart”,它应该返回以下 json:

{
    "version": "1.0.2",

    "students": ["Martin King"],

    "teachers": ["Martin Evans", "Leo Martin"],

    "authors" : ["Martin Fowler]
}

我怎样才能有效地做到这一点?谢谢你。

java json spring spring-boot
1个回答
0
投票

我们可以使用 java

HashMaps
来实现这一点。这是一个如何在春季执行此操作的示例。

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class SearchController {

    private final String jsonData = "{\n" +
            "    \"version\": \"1.0.2\",\n" +
            "    \"students\": [\"John Smith\", \"John Green\", \"Martin King\"],\n" +
            "    \"teachers\": [\"John Lord\", \"Martin Evans\", \"Steve John\", \"Gordon Lee\", \"Leo Martin\"],\n" +
            "    \"authors\" : [\"Martin Fowler\", \"Erich Gamma\"]\n" +
            "}";

    private final ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/search")
    public Map<String, Object> search(@RequestParam String keyword) {
        try {
            Map<String, Object> data = objectMapper.readValue(jsonData, HashMap.class);
            Map<String, Object> filteredData = new HashMap<>();
            filteredData.put("version", data.get("version"));
            filteredData.put("students", filterList((List<String>) data.get("students"), keyword));
            filteredData.put("teachers", filterList((List<String>) data.get("teachers"), keyword));
            filteredData.put("authors", filterList((List<String>) data.get("authors"), keyword));

            return filteredData;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    private List<String> filterList(List<String> list, String keyword) {
        return list.stream()
                .filter(item -> item.toLowerCase().contains(keyword.toLowerCase()))
                .collect(Collectors.toList());
    }
}

使用关键字

mart
向端点发送请求后,这是输出

{
    "version": "1.0.2",
    "students": ["Martin King"],
    "teachers": ["Martin Evans", "Leo Martin"],
    "authors": ["Martin Fowler"]
}
© www.soinside.com 2019 - 2024. All rights reserved.