有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring RestTemplate获取特定字段

我的安卓应用程序中有以下JSON,我正在使用Springs for 安卓 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"
    }
  ]
}

共 (3) 个答案

  1. # 2 楼答案

    如果Cast是一个POJO,那么可以尝试像这样使用Jackson ObjectMapper类

    ObjectMapper mapper = new ObjectMapper();
    String jsonStr = ...
    List<Cast> casts = mapper.readValue(jsonStr, new TypeReference<List<Cast>>(){});
    
  2. # 3 楼答案

    你可以像这样抓取、施放和转换场地:

        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);
        }