我正在使用 Jackson 库来解析 JSON:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Run Code Online (Sandbox Code Playgroud)
这是我正在做的事情:
public void testJackson() throws IOException {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
File from = new File("emp.txt"); // JSON object comes from
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};
HashMap<String, Object> o = mapper.readValue(from, typeRef);
Employees employees = new Employees();
employees.employees = (List<Employer>)o.get("employees"); // retrieving list of Employer(s)
employees.showEmployer(1); // choose second to print out to console
System.out.println("Got " + o); // just result of file reading
}
public static class Employees {
public List<Employer> employees;
public void showEmployer(int i) {
System.out.println(employees.get(i));
}
}
public static class Employer {
public String firstName;
public String lastName;
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出:
{名字=安娜,姓氏=史密斯}
得到了{员工=[{firstName=John,lastName=Doe},{firstName=Anna,lastName=Smith},{firstName=Peter,lastName=Jones}]}
但我并不期望 my 中的元素List是HashMap实例,而是Employer对象。这才是Jackson图书馆该有的样子,不是吗?你们能纠正我哪里错了吗?
我没有使用过 Jackson,但似乎你得到了你所要求的 - 字符串、对象对的 HashMap。也许您需要在地图的“价值”部分更加明确?由于该值是 Employee 对象的数组,您可以尝试:
TypeReference<HashMap<String, List<Employee>>> typeRef = new TypeReference<HashMap<String, List<Employee>>>() {};
HashMap<String, List<Employee>> o = mapper.readValue(from, typeRef);
Run Code Online (Sandbox Code Playgroud)