1. Use the default json to convert HttpessageConverter
At present, JSON is the mainstream front and back end data transmission mode. In spring MVC, HttpMessageConverter is used to support the conversion of JSON, and the relevant configuration is further simplified in spring boot.
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
By default, jacjson databind is added as the JSON processor in this dependency. At this time, you can return JSON without adding additional JSON processors.
public class Book { private String name; private String author; @JsonIgnore //Filter out this property protected Float price; @JsonFormat(pattern = "yyyy-MM-dd") //Format output this property private Date publicationDate; //ellipsis getter/setter }
@RestController public class BookController { @GetMapping("/book") public Book book() { Book book = new Book(); book.setAuthor("Luo Guanzhong"); book.setName("Romance of the Three Kingdoms"); book.setPrice(30f); book.setPublicationDate(new Date()); return book; } }
Result:
This is the processing method of spring boot. If you use this method, you can use annotations to ignore fields and format dates.
The mappingjackson 2httpmessageconverter provided by default in Spring implements json conversion.
2. Custom converter
In addition to Jackson databind, the common JSON processors include Gson and fastjson
2.1 use of Gson
Gson is an open-source JSON parsing framework of Google. Before using it, first remove the default Jackson databind, and then add the gson dependency.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
In spring boot, the automatic conversion class gsohttpmessageconverterconfiguration of Gson is provided by default, so you can use Gson directly like Jackson databind, but you need to customize HttpMessageConverter if you want to format date data during the conversion of Gson.
protected static class GsonHttpMessageConverterConfiguration { @Bean @ConditionalOnMissingBean public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); converter.setGson(gson); return converter; } }
@The ConditionalOnMissingBean annotation indicates that the default GsonHttpMessageConverter will be used when there is no GsonHttpMessageConverter provided in the project, so we can write a GsonHttpMessageConverter ourselves to avoid the default without GsonHttpMessageConverter.
@Configuration public class GsonConfig { @Bean GsonHttpMessageConverter gsonHttpMessageConverter() { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); GsonBuilder builder = new GsonBuilder(); //Set up Gson Format of date when parsing builder.setDateFormat("yyyy-MM-dd"); //Set up Gson The modifier when parsing is protected Filter out the fields of builder.excludeFieldsWithModifiers(Modifier.PROTECTED); //Establish Gson Object placement GsonHttpMessageConverter And return converter Gson gson = builder.create(); converter.setGson(gson); return converter; } }
public class Book {
private String name;
private String author;
protected Float price; //Fields filtered out
private Date publicationDate;
}
2.2 using fastjson
Alibaba's json parsing framework can be integrated into SpringBoot. Unlike Gson, fastjson cannot be used immediately after inheritance. Developers need to provide HttpMessageConverter before it can be used.
Similarly, remove the Jsckson databind dependency and add the fastjson dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
Configure HttpMessageConverter of fasjson
@Configuration public class MyFastJsonConfig { @Bean FastJsonHttpMessageConverter fastJsonHttpMessageConverter() { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); //Set up json Some details in parsing, date format, data coding config.setDateFormat("yyyy-MM-dd"); config.setCharset(Charset.forName("UTF-8")); //Are you building Json Output class name in //Is it output? value by null Data //Generated json Format //Empty set output[]Rather than null //Empty string output '' instead of null Other configuration config.setSerializerFeatures( SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty ); converter.setFastJsonConfig(config); return converter; } }
If the output Chinese is garbled: spring. Http. Encoding. Force response = true
There is another way to configure FastJsonHttpMessageConverter
After introducing spring boot starter web, he relies on spring boot autoconfigure. In this automatic configuration, a webmvcauautoconfiguration class provides the most basic configuration of spring MVC. If you want to configure yourself, you only need to implement the WebMvcConfigurer interface.
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer {@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd"); config.setCharset(Charset.forName("UTF-8")); config.setSerializerFeatures( SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty ); converter.setFastJsonConfig(config); converters.add(converter); }
}
Jackson notes:
When using Jackson related annotations, be sure to pay attention to whether the attribute naming defined by yourself is standard.
When naming is not standardized, it will lose effect. (for example, Ename, Eage is named for nonstandard. "Name" and "ageE" are named for the specification. If @ JsonIgnore annotation does not work, please pay attention to whether your attribute name is standardized
1,@JsonIgnoreProperties
This annotation is a class annotation. Its purpose is to ignore some properties in Java beans during json serialization. Serialization and deserialization are affected.
Write method add this label to the class name of the model class, you can have multiple attributes or a single attribute
//generate json When will name and age Attribute filtering @JsonIgnoreProperties({"name"},{"age"}) public class user { private String name; private int age; }
2,@JsonIgnore
This annotation is used for properties or methods (preferably properties), and has the same effect as @ JsonIgnoreProperties above.
Do not generate age property when generating json
public class user { private String name; @JsonIgnore private int age; }
3,@JsonFormat
This annotation is used for attributes or methods (preferably attributes). It is convenient to convert the Date type directly to the pattern we want, such as @ JsonFormat(pattern = "yyyy MM DD HH mm SS")
4,@JsonSerialize
This annotation is used on properties or getter methods to embed our custom code during serialization, such as limiting two decimal places after a double when serializing.
5,@JsonDeserialize
This annotation is used on the property or setter method to embed our custom code when deserializing, similar to @ JsonSerialize above
6,@Transient
If a property is not a field mapping of a database table, it must be marked as @ Transient. Otherwise, the ORM framework will default its annotation as @ Basic;
//Indicates that the field does not exist in the database table
@Transient public int getAge() { return 1+1; }