我在将项目转换为"学生"时遇到了一些麻烦。与Jackson ObjectMapper。我已经得到了基于前面发送的id参数实际获取正确项目的方法。所以这是有效的方法,但不会返回任何内容,因为我只想测试它是否有效。
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!
}
但是现在我需要它来返回一个&#34;学生&#34;,所以它应该返回学生而不是无效:
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;
}
答案 0 :(得分:1)
将item.get(&#34; payload&#34;)。getS()替换为&#34; item.getJSON(&#34; payload&#34;)。substring(1)&#34;。< / p>
答案 1 :(得分: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;
}