java - 将 JSON 数组解析为对象集合

标签 java json spring facebook-graph-api jackson

我在将 json 数组解析为指定对象的 java 集合时遇到问题。

JSON 响应:

{
  "data": [
    {
      "country_code": "US", 
      "name": "United States", 
      "supports_region": "true", 
      "supports_city": "true"
    }, 
    {
      "country_code": "CA", 
      "name": "Canada", 
      "supports_region": "true", 
      "supports_city": "true"
    }, 
    {
      "country_code": "GB", 
      "name": "United Kingdom", 
      "supports_region": "true", 
      "supports_city": "true"
    }
  ]
}

接下来我有单一国家的类(class):

@JsonIgnoreProperties(ignoreUnknown = true)
public class TargetCountry {

    @JsonProperty("country_code")
    private String countryCode;

    @JsonProperty("name")
    private String name;

    public String getCountryCode() {
        return countryCode;
    }

    public String getName() {
        return name;
    }

}

我正在使用 Jackson 库将 json 解析为 java。 如果没有包装数组的额外字段“数据”,一切都会好起来的。 由于“数据”字段,我不想制作额外的包装类。我如何以优雅的方式解析该响应以接收:Collection<TargetCountry>例如:

RestTemplate restTemplate = new RestTemplate();
TargetCountry[] countryList = restTemplate.getForObject(uri, TargetCountry[].class);

最佳答案

您可以考虑两种选择:

  • 使用 withRootName() 方法以忽略根“数据”节点的方式为您的剩余模板实例自定义 Jackson 对象映射器。您可能需要咨询 this question如何自定义映射器。
  • 将结果作为 JsonNode 读取,跳过“数据”路径并将其转换为对象数组。

例子如下:

public class JacksonRootValue {
    public static final String JSON = "{\n" +
            "  \"data\": [\n" +
            "    {\n" +
            "      \"country_code\": \"US\", \n" +
            "      \"name\": \"United States\", \n" +
            "      \"supports_region\": \"true\", \n" +
            "      \"supports_city\": \"true\"\n" +
            "    }, \n" +
            "    {\n" +
            "      \"country_code\": \"CA\", \n" +
            "      \"name\": \"Canada\", \n" +
            "      \"supports_region\": \"true\", \n" +
            "      \"supports_city\": \"true\"\n" +
            "    }, \n" +
            "    {\n" +
            "      \"country_code\": \"GB\", \n" +
            "      \"name\": \"United Kingdom\", \n" +
            "      \"supports_region\": \"true\", \n" +
            "      \"supports_city\": \"true\"\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class TargetCountry {
        @JsonProperty("country_code")
        public String countryCode;
        public String name;

        @Override
        public String toString() {
            return "TargetCountry{" +
                    "countryCode='" + countryCode + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper1 = new ObjectMapper();
        // customize the mapper
        mapper1.setConfig(mapper1.getDeserializationConfig().withRootName("data"));
        TargetCountry[] result1 = mapper1.readValue(JSON, TargetCountry[].class);
        System.out.println("Option 1: " + Arrays.toString(result1));

        // read as a JsonNode and then convert to an object
        ObjectMapper mapper2 = new ObjectMapper();
        JsonNode node = mapper2.readValue(JSON, JsonNode.class);
        TargetCountry[] result2 = mapper2.treeToValue(node.path("data"), TargetCountry[].class);
        System.out.println("Option 2: " + Arrays.toString(result2));
    }
}

输出:

Option 1: [TargetCountry{countryCode='US', name='United States'}, TargetCountry{countryCode='CA', name='Canada'}, TargetCountry{countryCode='GB', name='United Kingdom'}]
Option 2: [TargetCountry{countryCode='US', name='United States'}, TargetCountry{countryCode='CA', name='Canada'}, TargetCountry{countryCode='GB', name='United Kingdom'}]

关于java - 将 JSON 数组解析为对象集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24507858/

相关文章:

java - MainActivity.java : uses or overrides a deprecated API

java - 比较 boolean 值时,JUnit Mockito 在assertEquals 中始终返回 false

java - 如何检查某个元素的功能是否包含在集合中?

json - jq - 根据子元素的搜索结果查找父元素

java - 错误[org.jboss.msc.service.fail](MSC服务线程1-3)MSC000001 : Failed to start service jboss.部署.单元。 .POST_MODULE

java - Swagger2 : Failed to introspect Class [springfox. 文档.swagger2.configuration.Swagger2DocumentationConfiguration]

java - 如何在运行时从文件夹加载 jar 文件并在 JBoss EAP 6.0.1 中实例化类

android - 在 Android 上将 JSON 从 String 加载到 JSONArray

json - ORM : Sequelize: How can I return except some json data?

java - 如何在 Spring Integration 的入站网关中接受 MultipartFile