搜索 JSON 数据中的字符串并以 JSON 形式返回子集

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

我正在开发 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
2个回答
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"]
}

0
投票

您可以创建一个名为

Result
的记录/POJO,它与 JSON 数据同步,并过滤字段。

这是一种不可变/函数式方法:

import java.util.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class FilterJSON {
    public record Result(String version, List<String> students, List<String> teachers, List<String> authors) {}

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws JsonProcessingException {
        String data = """
                {
                    "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"]
                }
                """;

        Result result = objectMapper.readValue(data, Result.class);
        Result filtered = filter(result, "mart");
        System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(filtered));
    }

    public static Result filter(Result result, String term) {
        String criteria = term.toLowerCase();
        List<String> students = filterList(result.students(), criteria);
        List<String> teachers = filterList(result.teachers(), criteria);
        List<String> authors = filterList(result.authors(), criteria);
        return new Result(result.version(), students, teachers, authors);
    }

    private static List<String> filterList(List<String> list, String term) {
        return list.stream()
                .filter(name -> Optional.ofNullable(name)
                        .map(String::toLowerCase)
                        .orElse("")
                        .contains(term))
                .toList();
    }
}

结果

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