0

我在使用 Jackson ObjectMapper 将我的项目转换为“学生”时遇到了一些麻烦。我已经获得了基于从前面发送的 id 参数实际获取正确项目的方法。所以这是有效的方法,但不返回任何东西,因为我只是想测试它是否有效。

AWS 服务:

public void getStudent(String id){

    Table t = db.getTable(studentTableName);

    GetItemSpec gio = new GetItemSpec()
            .withPrimaryKey("id", id);

    Item item = t.getItem(gio);
    System.out.println("Student: "+item); // <--- Gives the correct item!

}

但现在我需要它返回一个“学生”,所以它应该返回一个学生,而不是 void:

public Student getStudent(String id){

    Table t = db.getTable(studentTableName);

    GetItemSpec gio = new GetItemSpec()
            .withPrimaryKey("id", id);

    Item item = t.getItem(gio);

    //Problem starts here, unsure of how to do. As is, getS() is underlined as error
    Student student = mapper.readValue(item.get("payload").getS(), Student.class);

    return student;
}

作为参考,我将添加检索所有学生的工作方法。如您所见,我尝试使用与检索所有学生的方法相同的 mapper.readValue:

public List<Student> getStudents() {

    final List<Student> students = new ArrayList<Student>();

    ScanRequest scanRequest = new ScanRequest()
            .withTableName(studentTableName);

    ScanResult result = client.scan(scanRequest);
    try {
        for (Map<String, AttributeValue> item : result.getItems()) {
            Student student = mapper.readValue(item.get("payload").getS(), Student.class);
            students.add(student);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return students;
}
4

2 回答 2

1

将 item.get("payload").getS() 替换为 "item.getJSON("payload").substring(1)"。

于 2016-06-02T10:06:35.197 回答
0

我想到了。这是我的正确方法:

public Student getStudent(String id) throws JsonParseException, JsonMappingException, IOException  {

    Table t = db.getTable(studentTableName);

    GetItemSpec gio = new GetItemSpec()
            .withPrimaryKey("id", id);

    Item item = t.getItem(gio);

    Student student = mapper.readValue(StringEscapeUtils.unescapeJson(item.getJSON("payload").substring(1)), Student.class);

    return student;

}
于 2016-06-03T04:04:22.080 回答