【问题标题】:How to send pure JSON object (which resided inside model object) to view in spring boot?如何发送纯 JSON 对象(位于模型对象内)以在 Spring Boot 中查看?
【发布时间】:2021-04-11 04:55:00
【问题描述】:

我是 Spring Boot 开发的新手。我必须将我的 json 对象放在我的模型对象中并将其发送到视图。我使用杰克逊库的 ObjectMapper 类将对象转换为字符串。

我的控制器 sn-p 是

@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";
}

我的模型类是

@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

在视图方面,我有下面的百里香代码来访问 JSON 对象

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

但是在控制台窗口上,我最终得到了这个......

{&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}

如何将 JSON 字符串传递到前端,以便我可以使用 Javascript 访问它而无需进行 html 解码。

【问题讨论】:

    标签: javascript json spring spring-boot jackson


    【解决方案1】:

    我了解到您正在将 JSON 对象转换为字符串并将其设置在模型中。这显然是在前端生成字符串,而不是您可以直接在响应中发送模型对象。无论如何,它最终都会生成 JSON 数据。

    @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";
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      相关资源
      最近更新 更多