2012-11-27 56 views
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圖書館應該是,不是嗎?你們能糾正我的錯誤嗎?

回答

4

我還沒有使用過傑克遜,但看起來你得到了你所要求的 - 一個String,Object對的HashMap。也許你需要在地圖的「價值」部分更加明確?由於該值是Employee對象的數組,因此您可以嘗試:

TypeReference<HashMap<String, List<Employee>>> typeRef = new TypeReference<HashMap<String, List<Employee>>>() {}; 
HashMap<String, List<Employee>> o = mapper.readValue(from, typeRef); 
相關問題