根据 id 从 DynamoDB 中检索项目并转换项目

Retrieving an item from DynamoDB based on id and transforming the item

我在使用 Jackson ObjectMapper 将我的项目转换为 "Student" 时遇到了一些麻烦。我已经得到了根据从前面发送的 id 参数实际获得正确项目的方法。所以这是有效的方法,但没有 return 任何东西,因为我只是想测试它是否有效。

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!

}

但现在我需要它 return 一个 "Student",所以它应该 return 一个学生:

而不是 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;
}

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

我明白了。这是对我来说正确的方法:

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;

}