From the previous section: Springboot 02_ returns JSON data and can return JSON data, since some people are accustomed to different JSON frameworks, such as Fastjson, Here's how to integrate Fastjson in Springboot to enable JSON serialization of data.
There are two ways to integrate when using Fastjson, but you need to introduce a Fastjson dependency package
1: Introduction of Fastjson Dependency Packages
<Dependency> <groupId>Com.alibaba</groupId> <Artifactid>Fastjson</Artifactid> <version>1.2.31</version></Dependency>
2: New User.java
@Data Public classUser {//name PrivateString name; //Age PrivateInteger age; //Birthday PrivateLocalDateTime birthday; //Notes PrivateString remark;}
3: Integrated Fastjson
1: Way One
- Start class Inheritance extends Webmvcconfigureradapter
- Coverage Method Configuremessageconverters
Startup class:
@SpringBootApplication Public classFastjsonapplicationoneextendswebmvcconfigureradapter{/*** Register Fastjson type converter here, need version 1.2.10 after * way one: * by inheriting Webmvcconfigureradapter, then adding Converter *@paramConverters*/@Override Public voidConfiguremessageconverters (listconverters) { Super. Configuremessageconverters (converters); Fastjsonhttpmessageconverter Fastjsonhttpmessageconverter=NewFastjsonhttpmessageconverter (); Fastjsonconfig Fastjsonconfig=NewFastjsonconfig (); Fastjsonconfig.setserializerfeatures (Serializerfeature.prettyformat); Fastjsonhttpmessageconverter.setfastjsonconfig (Fastjsonconfig); Converters.add (Fastjsonhttpmessageconverter); } Public Static voidMain (string[] args) {Springapplication.run (fastjsonapplicationone.class, args); }}
2: Way Two
- In the App.java startup class, inject Bean:httpmessageconverters
Start class
@SpringBootApplication Public classFastjsonapplicationtwo { Public Static voidMain (string[] args) {Springapplication.run (fastjsonapplicationtwo.class, args); } @Bean httpmessageconverters Fastjsonhttpmessageconverters () {Fastjsonhttpmessageconverter FastJsonHttpMessa Geconverter=NewFastjsonhttpmessageconverter (); Fastjsonconfig Fastjsonconfig=NewFastjsonconfig (); Fastjsonconfig.setserializerfeatures (Serializerfeature.prettyformat); Fastjsonhttpmessageconverter.setfastjsonconfig (Fastjsonconfig); Httpmessageconverter<?> converter =Fastjsonhttpmessageconverter; return Newhttpmessageconverters (Converter); }}
Writing of the 4:controller class
@RestController @requestmapping ( "/fastjson" " public class Fastjsoncontroller {@GetMapping ( "/getuser" " public User GetUser () {user User = new user (); User.setname ( "Bob" 5 "This is remark.") return user; }}
5: Perform the Main method of Fastjsonapplicationone and Fastjsonapplicationtwo respectively, enter: Lcoalhost:8080/fastjson/getuser to test:
If you can return the above results, congratulations, you can already use Springboot integrated Fastjson to JSON the returned data.
Springboot 03_ using Fastjson to return JSON data