I'm having a bit of trouble with transforming my item to a "Student" with Jackson ObjectMapper. I've gotten the method to actually get the right item based on the id-parameter sent from the front. So this is the method that works, but doesn't return anything, because I just wanted to test if it works.
AwsService:
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!
}
But now I need it to return a "Student", so instead of void, it should return a Student:
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;
}
Just as a reference I'll add my working method for retrieving all students. So as you can see, I tried to use the same mapper.readValue as in the method for retrieving all students:
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;
}
I figured it out. Here is the correct method for me:
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;
}