我会为拥有客户列表和 getter/setter 对的客户创建一个 POJO,如下所示:
class CustomersFile{
List<Customer> customers;
//getter and setter
}
然后我将使用字段名称和 customerDetails 创建类 Customer,如下所示:
class Customer {
String name;
CustomerDetails details;
//getters and setters for both fields
}
最后,我将创建包含所有字段的类 CustomerDetails,如下所示:
class CustomerDetails {
String name;
String telephone;
int pi; // and so on
//getters and setters for all fields
}
然后使用对象映射器,我会将所有客户从 json 映射到我的 CustomersFile 对象:
ObjectMapper mapper = new ObjectMapper();
//this configuration is needed in case you have only one customer in your json.
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
CustomersFile customersFile = mapper.readValue(pathCustomerFile, CustomersFile.class);
要访问客户列表,只需调用:
List<Customer> customers = customersFile.getCustomers();
如果你真的需要一个 HashMap 然后遍历列表并填充这个哈希图:
HashMap<String, Customer> map = new HashMap<>();
for(Customer customer : customers) {
// as string you can use the id of the customer (pi) but its no necessary, just use your desired String
map.put("String.valueOf(customer.getPi())", customer);
}
更新
以下是我在项目的 pom 中使用的依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>