Spring-Boot est basé sur le cadre de printemps. Ce n'est pas une amélioration de la fonctionnalité du cadre de ressort, mais un moyen de construire rapidement le ressort.
L'application Spring-Boot fournit le convertisseur JSON par défaut pour Jackson. Exemple:
Configuration de dépendance dans pom.xml:
<project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd "> <ModelVersion> 4.0.0 </ ModelVersion> <proupId> com.qinker </prouvenid> <ArtifActid> printemps-boot </ artifactive> <packaging> war </packaging> <parent> <proupId> Org.spring <ArtefactId> Spring-Boot-Starter-Parent </ ArfactId> <Dersion> 2.0.0.release </Se version> </parent> <version> 0.0.1-snapshot </maven.apache.org </rom> <url> http://maven.apache.org </url> <url> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> <java.version> 9 </java.version> </properties> <Dendecces> <! - https://mvnrepository.com/artifact/org.springframe <GroupId> org.springframework.boot </prôdId> <Ertifactid> printemps-boot-starter-web </retifactid> </dependency> </dpendance> <uild> <inalName> Spring-Boot </inalName> </uild> </rand>
Créez trois classes: mainapp.java et user.java et hellocontroller.java:
package com.springboot; Importer java.util.date; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restController; @RestController Public classe HelloController {@RequestMapping ("/ Hello") String public hello () {return "Hello, Springboot"; } / ** * Spring Boot Le cadre de résolution JSON par défaut est Jackson * @return * / @requestmapping ("/ getuser") public utilisateur GetUser () {user u = new User (); U.SetName ("Zhang San"); U.Setage (33); U.SetCreateTime (new Date ()); retourne u; }} package com.springboot; import java.io.serializable; Importer java.util.date; La classe publique utilisateur implémente Serializable {Nom de chaîne privée; Âge privé; Date privée CreateTime; public String getName () {Nom de retour; } public void setName (string name) {this.name = name; } public int getage () {return âge; } public void Setage (int Age) {this.age = age; } public Date getcreatetime () {return CreateTime; } public void setCreateTime (date CreateTime) {this.createtime = CreateTime; }} package com.springboot; import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.springbootapplication; @SpringBootApplication Public Classe MainApp {public static void main (String [] args) {SpringApplication.run (mainApp.class, args); }}Démarrez MainApp: Visitez http: // localhost: 8080 / getuser, le résultat est le suivant:
{"Name": "Zhang San", "Age": 33, "CreateTime": "2018-04-04T03: 03: 08.534 + 0000"}On peut voir que nous n'avons fait aucune configuration, mais nous avons renvoyé les données JSON. On peut voir que Spring-Boot a fait une implémentation par défaut de JSON et utilise le convertisseur Jackson intégré.
Alors, prenons Fastjson comme exemple:
Tout d'abord, introduisez le package Fastjson et ajoutez les dépendances suivantes dans le POM:
<! - https://mvnrepository.com/artifact/com.alibaba/fastjson -> <dependency> <proupId> com.alibaba </rom grouped> <artifactId> FastJson </artifactid> <version> 1.2.47 </-version> </dependency>
Pour faciliter l'effet, modifiez la classe utilisateur:
package com.springboot; import java.io.serializable; Importer java.util.date; import com.alibaba.fastjson.annotation.jsonfield; @SuppressWarnings ("SERIAL") La classe publique User implémente Serializable {Private String Name; Âge privé; @Jsonfield (format = "yyyy-mm-dd hh: mm") datte privé CreateTime; public String getName () {Nom de retour; } public void setName (string name) {this.name = name; } public int getage () {return âge; } public void Setage (int Age) {this.age = age; } public Date getcreatetime () {return CreateTime; } public void setCreateTime (date CreateTime) {this.createtime = CreateTime; }}1. La première façon d'implémenter la conversion JSON personnalisée FastJSON, Spring-Boot implémente l'interface WebMVCConventers:
Modifiez MainApp comme suit:
package com.springboot; import java.util.arraylist; Importer java.util.list; import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.http.mediaType; import org.springframework.http.converter.httpMessageConverter; import org.springframework.web.servlet.config.annotation.webmvcConfigurer; import com.alibaba.fastjson.serializer.serializerfeature; import com.alibaba.fastjson.support.config.fastjsonconfig; import com.alibaba.fastjson.support.spring.fastjsonhttpMessageConverter; @SpringBootApplication Public Class MainApp implémente webmvcConfigurer {@Override public void configureMessageConverters (list <httpMessageConverter <? >> Converters) {webmvcconfigurer.super.configureMessageConverters (converters); // Créer une instance de convertisseur FastJSON FastJSonHttpMessageConverter Converter = new FastJSonHttpMessageConverter (); // Objet de configuration FastJSonConfig config = new FastJSonConfig (); List <diasyType> mediaTypes = new ArrayList <> (); // Encodage chinois MediaType MediaType = mediaType.Application_JSON_UTF8; MediaTypes.Add (MediaType); config.setSerializerFeatures (SerializerFeatur.prettyformat); convertisseur.SetSupportedMediaTypes (MediaTypes); converter.setfastjsonconfig (config); convertisseurs.add (convertisseur); } public static void main (String [] args) {springApplication.run (mainApp.class, args); }}Démarrez le programme: accédez au chemin ci-dessus: le navigateur verra les résultats suivants:
{"Age": 33, "CreateTime": "2018-04-04 11:14", "nom": "Zhang San"} 2. Inject FastJson Convertisseur Utilisation de @Bean Annotation: Modifiez MainApp comme suit:
package com.springboot; import java.util.arraylist; Importer java.util.list; import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.boot.autoconfigure.http.httpMessageConverters; import org.springframework.context.annotation.bean; import org.springframework.http.mediaType; import com.alibaba.fastjson.serializer.serializerfeature; import com.alibaba.fastjson.support.config.fastjsonconfig; import com.alibaba.fastjson.support.spring.fastjsonhttpMessageConverter; @SpringBootApplication Public Class mainApp {@Bean public httpMessageConverters FastJSonHttpMessageConventers () {FastJSonHttPMessageConverter Converter = new FastJsonHttpMessageConverter (); FastJSonConfig config = new FastJsonConfig (); config.setSerializerFeatures (SerializerFeatur.prettyformat); List <diasyType> mediaTypes = new ArrayList <> (); mediatypes.add (mediatype.application_json_utf8); convertisseur.SetSupportedMediaTypes (MediaTypes); Renvoie un nouveau HTTPMessageConverters (convertisseur); } public static void main (String [] args) {springApplication.run (mainApp.class, args); }}Le résultat d'accès est le même.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.