在SpringBoot JPA方法中将Java对象转换为字符串

Joh*_*een 1 java spring-data-jpa spring-boot

我正在使用Springboot MySQL示例(类似示例)。在其中一种方法中,我想记录JSON数据,但我得到了,

com.example.employee.model.Employee@1595ddd2

@RequestMapping(value="/employees12/{id}", method=RequestMethod.GET)
public Employee getPerson(@PathVariable Long id){
    Employee employee = employeeRepository.findOne(id);
    //String str=employee.toString();
    //System.out.println("string is " + str);
    System.out.println(employee); //print json in logs console
    return employee;
}
Run Code Online (Sandbox Code Playgroud)

return employees;是给JSON数据。我尝试过toString(),即使这样也不起作用。任何帮助表示赞赏。

Sar*_*van 5

您可以使用writerWithDefaultPrettyPrinterfrom ObjectMapper。这样可以进行漂亮的打印。

private ObjectMapper mapper = new ObjectMapper();

@RequestMapping(value="/employees12/{id}", method=RequestMethod.GET)
public Employee getPerson(@PathVariable Long id){
    Employee employee = employeeRepository.findOne(id);
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee));
    return employee;
}
Run Code Online (Sandbox Code Playgroud)

如果仅在紧凑模式下输出,请使用 writeValueAsString

System.out.println(mapper.writeValueAsString(employee));
Run Code Online (Sandbox Code Playgroud)