javascriptjsonspringspring-bootjackson

How to send pure JSON object (which resided inside model object) to view in spring boot?


I'm new to spring boot development. I have to put my json object inside my model object and send it to view. I've used jackson library's ObjectMapper class to convert the object into String.

My controller snippet is

@GetMapping("/show-employee")
public String showEmployee(Model model) {
    ObjectMapper objectMapper = new ObjectMapper();
    String empString = objectMapper.writeValueAsString(new Employee("santhosh", "kumar", "example@gmail.com"))
    model.addAttribute("employee", empString);
    return "employees/employee-display";
}

And my model class is

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    @NotBlank
    @Size(min = 3, max = 20)
    private String firstName;

    @NotBlank
    @Size(min = 3, max = 20)
    private String lastName;
    
    @Email(message = "Please enter a valid email id")
    private String email;

    // constructors, getters and setters

On the view side, I have thymeleaf code as below to access the JSON object

<script>
        var employeesJsonStr = "[[${employee}]]";
        console.log(employeesJsonStr);
</script>

But on the console window, I end up with this...

{&quot;id&quot;:0,&quot;firstName&quot;:&quot;santhosh&quot;,&quot;lastName&quot;:&quot;kumar&quot;,&quot;email&quot;:&quot;example@gmail.com&quot;,&quot;projects&quot;:null}

How can pass the JSON String to front end so that I can access that using Javascript without having to do html decoding.


Solution

  • I understand you are converting JSON object as string and setting it up inside a model. This is obviously produce String in the frontend. Instead, you can directly send the model object in the response. It will produce JSON data at the frontend.

    @GetMapping("/show-employee" , produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Employee> showEmployee(Model model) {
        Employee emp = new Employee("santhosh", "kumar", "example@gmail.com"))
        model.addAttribute("employee", emp);
        return "employees/employee-display";
    }