java將物件轉為json的方式

NewTimeProgramer發表於2020-12-20

概述

java將物件轉為json字串一般有兩種方式:
1.jackson
2.fastjson

jackson

1.引入依賴

<dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-databind</artifactId>
           <version>2.11.1</version>
 </dependency>

2.接下來就將user物件轉成json字串

ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(user);

fastjson

1.引入依賴

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

2.接下來將user物件轉成json字串

String s = JSON.toJSONString(user);

配置springmvc自動將物件轉為json字串

1.springmvc的配置檔案新增

<mvc:annotation-driven/>

2.新增jackson依賴

		<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.10.1</version>
        </dependency>

3.在相應的controller類上加上註解

@ResponseBody

相關文章