【问题标题】:Spring RestTemplate jackson fetch particular fieldSpring RestTemplate jackson 获取特定字段
【发布时间】:2025-11-23 18:30:04
【问题描述】:

我的 android 应用程序中有以下 JSON,我正在使用 Springs for android RestTemplate。是否有可能从这个 json 中只获取内部列表?目前我必须创建一个包装对象,然后我可以从中获取List<Cast> casts; - 这有点不方便。

{
  "id": 550,
  "cast": [
    {
      "cast_id": 4,
      "character": "The Narrator",
      "credit_id": "52fe4250c3a36847f80149f3",
      "id": 819,
      "name": "Edward Norton",
      "order": 0,
      "profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
    }
  ]
}

【问题讨论】:

    标签: java json spring jackson


    【解决方案1】:

    您可以像这样抓取字段、投射和转换它:

        final String json = "{\n" +
                "  \"id\": 550,\n" +
                "  \"cast\": [\n" +
                "    {\n" +
                "      \"cast_id\": 4,\n" +
                "      \"character\": \"The Narrator\",\n" +
                "      \"credit_id\": \"52fe4250c3a36847f80149f3\",\n" +
                "      \"id\": 819,\n" +
                "      \"name\": \"Edward Norton\",\n" +
                "      \"order\": 0,\n" +
                "      \"profile_path\": \"/iUiePUAQKN4GY6jorH9m23cbVli.jpg\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
    
        final List<Cast> casts;
        try {
            final JsonNode cast = objectMapper.readTree(json).get("cast");
            casts = objectMapper.convertValue(cast, new TypeReference<List<Cast>>() {});
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    

    【讨论】:

      【解决方案2】:

      如果Cast 是 POJO,您可以尝试像这样使用 Jackson ObjectMapper 类

      ObjectMapper mapper = new ObjectMapper();
      String jsonStr = ...
      List<Cast> casts = mapper.readValue(jsonStr, new TypeReference<List<Cast>>(){});
      

      【讨论】:

        【解决方案3】:

        我知道解决这个问题的两种解决方案:

        1. 你做了什么:使用类包装列表
        2. 写你自己的 JSON Deserializer,看这里http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

        但我认为最终的解决方案在这篇文章中: Spring/json: Convert a typed collection like List<MyPojo>

        【讨论】: