Reputation: 731
I am working on Springboot MySQL example(Similar example). In one of the methods, I want to log JSON data but I am getting,
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;
}
The return employees;
is giving JSON data.
I have tried toString(), even that doesnt work. Any help is appreciated.
Upvotes: 3
Views: 16281
Reputation: 2013
You can use google gson library:
@Override
public String toString() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
Upvotes: -1
Reputation: 8032
You can use writerWithDefaultPrettyPrinter
from ObjectMapper
. This enables pretty print.
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;
}
If you want the output just in compact mode, use writeValueAsString
System.out.println(mapper.writeValueAsString(employee));
Upvotes: 6
Reputation: 16908
In the getPerson() method, use objectMapper.writeValueAsString()
to get the JSON of the employee object:
@RequestMapping(value="/employees12/{id}", method=RequestMethod.GET)
public Employee getPerson(@PathVariable Long id){
Employee employee = employeeRepository.findOne(id);
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(employee));
return employee;
}
Adding a toString()
in Employee class, with the ObjectMapper
from Jackson to serialize the Employee instance. The advantage of overriding the toString()
method in the Employee class is you can just do System.out.println(employee);
anywhere to get the JSON representation of the Employee object.
public String toString(){
String serialized ="";
try{
ObjectMapper objectMapper = new ObjectMapper();
serialized = objectMapper.writeValueAsString(this);
}catch(JsonProcessingException jpe){
jpe.printStackTrace();
}
return serialized;
}
Upvotes: 1