java—在SpringBootWeb应用程序中如何将响应转换为json?

5t7ly7z5  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(315)

我还没有包括在我的pomJackson数据绑定。然而,当我调用一个返回对象的端点时,它会被转换成json。如果我的pom不包含jackson数据绑定,那么如何将响应转换为json。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
    <relativePath />
</parent>

<dependencies>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

@restcontroller公共类tradecontroller{

@RequestMapping("/trade")
public Trade hello() {
    String helloWorldMessage = "Hello world from java2blog!";
    Trade t = new Trade();
    t.setId(1);
    return t;
}

}
打电话http://localhost:8080/交易返回{“id”:1}

z31licg0

z31licg01#

如果你跑了 mvn dependency:tree ,您将看到默认情况下包含在 spring-boot-starter-web 附属国。请注意,包含了jackson数据绑定。
前任:

[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.4.3:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-json:jar:2.4.3:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.11.4:compile
[INFO] |  |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.11.4:compile
[INFO] |  |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.11.4:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.11.4:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.11.4:compile
[INFO] |  |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.11.4:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.4.3:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.43:compile
[INFO] |  |  +- org.glassfish:jakarta.el:jar:3.0.3:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.43:compile
[INFO] |  +- org.springframework:spring-web:jar:5.3.4:compile
[INFO] |  |  \- org.springframework:spring-beans:jar:5.3.4:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:5.3.4:compile
[INFO] |     +- org.springframework:spring-aop:jar:5.3.4:compile
[INFO] |     \- org.springframework:spring-expression:jar:5.3.4:compile

在幕后,spring利用jackson模块将您的响应转换为json。

3mpgtkmj

3mpgtkmj2#

答案是

@RestController
@RequestMapping(value = "mycontroller")
public class MyController {

    @RequestMapping(value = "/trade")
    @ResponseBody
    public ResponseEntity<String> hello() {
     JSONObject res = new JSONObject();
     String helloWorldMessage = "Hello world from java2blog!";
     Trade t = new Trade();
     t.setId(1);
     res.put("student Object",t);
     return new ResponseEntity<>(res.toString(),HttpStatus.OK);
 }

}

相关问题