0

我正在使用 Jackson 库来解析 JSON:

{
"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;
}

我得到的输出:

{名=安娜,姓=史密斯}

得到 {employees=[{firstName=John, lastName=Doe}, {firstName=Anna, lastName=Smith}, {firstName=Peter, lastName=Jones}]}

但我不希望我的元素ListHashMap实例,而是Employer对象。这就是Jackson图书馆应该是的,不是吗?你们能纠正我哪里错了吗?

4

1 回答 1

4

我没有使用杰克逊,但似乎你得到了你所要求的 - 一个字符串,对象对的 HashMap。也许您需要在地图的“价值”部分更加明确?由于该值是一个 Employee 对象数组,您可以尝试:

TypeReference<HashMap<String, List<Employee>>> typeRef = new TypeReference<HashMap<String, List<Employee>>>() {};
HashMap<String, List<Employee>> o = mapper.readValue(from, typeRef);
于 2012-11-27T22:49:26.517 回答