简体   繁体   English

春天开机CONTROLER响应JSON对象

[英]Spring boot controler response Json object

I am new to spring boot and trying to learn it. 我是Spring Boot的新手,正在尝试学习它。 I tried the example with the RESTful service where one gets a JSON object from the controller as response. 我使用RESTful服务尝试了该示例,该服务从控制器获取一个JSON对象作为响应。 With the web address provided it works. 使用提供的网址即可使用。

But when i run it against a local controller in a spring boot installation on tomcat i only get a String array not a JSON object as response. 但是,当我在tomcat的春季启动安装中针对本地控制器运行它时,我只得到一个String数组而不是一个JSON对象作为响应。

I know you need to have a JSON mapper class in the project ( Jackson - mapper ). 我知道您需要在项目(Jackson-mapper)中有一个JSON映射器类。 But in the example its defined how to include that. 但是在示例中,它定义了如何包括该内容。

I looked here and at Google but found nothing about how to include the mapper. 我在这里和Google处看过,但对如何包含映射器一无所知。 Can someone tell me what i must do to get a JSON object in the response body from the controller or where to look? 有人可以告诉我我该怎么做才能从控制器的响应主体中获取JSON对象,或者在哪里看? Any advise welcome. 任何建议欢迎。

Khelvan Code Controller Khelvan代码控制器

 @RequestMapping("/greeting")
    @ResponseBody
  public String ajaxGreetings(
    //  @RequestParam("name") String p_name
) {
    String json = "{\"id\":2488,\"content\":\"Hello!\"}";


    return json;
}

Ajax in Html HTML中的Ajax

$.ajax({
   //     url: "http://rest-service.guides.spring.io/greeting"
      url: "http://host.org:8080/greeting"
    }).then(function(data) {
       $('.greeting-id').append(data.id);
       $('.greeting-check').append(data);
       $('.greeting-content').append(data.content);
    });

Any Advise what is missing? 有什么建议吗?

Thanks and best regards 谢谢和最好的问候

Khel 凯尔

I solved the problem. 我解决了问题。 Its necessary to retrun a java Class containing the data as attributes from the controller not a json String. 有必要从控制器(而不是json字符串)重新运行包含数据作为属性的java类。 Spring convertes the return to json format and does only funtions when one returns a class here. Spring将return转换为json格式,并且仅当返回此处的类时才执行功能。

Best regards. 最好的祝福。

Khel. 凯尔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM