0
我使用的是傑克遜庫來解析JSON:用Jackson解析JSON。爲什麼使用HashMap而不是我的類型?
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
下面是我在做什麼:
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;
}
輸出我得到:
{的firstName = Anna,lastName = Smith}
Got {employees = [{firstName = John, lastName = Doe},{firstNam E =安娜,姓氏=史密斯},{=的firstName彼得, 的lastName =瓊斯}]}
但我不期待在我的List
元素是HashMap
實例,但Employer
對象。這是什麼Jackson
圖書館應該是,不是嗎?你們能糾正我的錯誤嗎?