代码之家  ›  专栏  ›  技术社区  ›  ambuli

在Java中,在JSON中搜索字符串并以JSON形式返回子集

  •  0
  • ambuli  · 技术社区  · 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"]
    }
    

    我如何才能有效地做到这一点?非常感谢。

    0 回复  |  直到 1 年前
        1
  •  2
  •   Mr. Polywhirl    1 年前

    您可以创建一个名为 Result 它与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" ]
    }
    
        2
  •  1
  •   SamHoque    1 年前

    我们可以使用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"]
    }