John Seen
John Seen

Reputation: 731

Convert Java Object to String in SpringBoot JPA Method

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

Answers (3)

user666
user666

Reputation: 2013

You can use google gson library:

    @Override
public String toString() {
    return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}

Upvotes: -1

1218985
1218985

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

Amardeep Bhowmick
Amardeep Bhowmick

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

Related Questions