Article directory
Jiang Shuai, Naixue education, is good at system architecture design, big data, operation and maintenance and other technical fields; has rich experience in large and medium-sized background technology (transaction platform, basic service, intelligent customer service, infrastructure, intelligent operation and maintenance, database, security, IT and other directions); once served as Huaizhi Technology CTO, and also in Neusoft group, China Mobile, Dodi group and other enterprises in charge of relevant technology.
Handling JSON data
JSON is the current mainstream front-end and back-end data transmission method. When the Controller returns a Java object or List collection, Spring Boot will automatically convert it to JSON data.
Spring Boot has built-in JSON parsing function. When you add the Spring Boot starter web module in the project, you can see that it contains Jackson parser by default, or you can replace it with Fastjson and other parsers.
1. Edit the Book class
public class Book { private Integer id; private String name; private String author; @JsonIgnore private Float price; @JsonFormat(pattern = "yyyy-MM-dd") private Date bookPublicationDate; // getter and setter methods }
2. Edit BookController controller
When returning data, you need to use the @ ResponseBody annotation. If @ Controller and @ ResponseBody annotations are often used, the @ RestController composite annotation can be used instead.
@RestController public class BookController { @GetMapping("/book") public Book book(){ Book book = new Book(); book.setId(1); book.setName("<Manon turns over: adding material to technology with stories"); book.setAuthor("Liu Xin"); book.setPrice(69f); book.setBookPublicationDate(new Date()); return book; } }
After running, visit http://localhost:8080/book in the direct address bar to see the returned JSON data.
3. Convert set data
Add the getBooks() method, create a List collection, and store three books. The specific source code is as follows:
@RequestMapping("/getBooks") public List<Book> getBooks() { List<Book> bookList = new ArrayList<>(); Book book1 = new Book(); book1.setId(1); book1.setName("<Manon turns over: adding material to technology with stories"); book1.setAuthor("Liu Xin"); book1.setPrice(69f); book1.setBookPublicationDate(new Date()); Book book2 = new Book(); book2.setId(2); book2.setName("<Comics algorithm: Xiaohui's algorithm journey (full color)"); book2.setAuthor("Wei Meng Shu"); book2.setPrice(79f); book2.setBookPublicationDate(new Date()); Book book3 = new Book(); book3.setId(3); book3.setName("<Future architecture"); book3.setAuthor("Zhang Liang"); book3.setPrice(99f); book3.setBookPublicationDate(new Date()); bookList.add(book1); bookList.add(book2); bookList.add(book3); return bookList; }
After running, visit http://localhost:8080/getBooks in the direct address bar, and you can see that the getBooks() method creates multiple Book objects to be encapsulated in the List collection and returns JSON data to the client.
4. Replace the converter
1) Use Gson
Gson is Google's open-source JSON parser. When adding dependencies, you should first remove the default jackson, as follows:
<!-- Appoint web Dependency module --> <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> <!-- gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
During Gson conversion, if you need to format date data, you need to customize HttpMessageConverter, and then provide a GsonHttpMessageConverter, as follows:
@Configuration public class GsonConfig { @Bean GsonHttpMessageConverter gsonHttpMessageConverter() { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("yyyy-MM-dd"); builder.excludeFieldsWithModifiers(Modifier.PROTECTED); Gson gson = builder.create(); converter.setGson(gson); return converter; } }
Modify the Book class as follows:
public class Book { private Integer id; private String name; private String author; protected Float price; private Date bookPublicationDate; // getter and setter methods }
After running, visit http://localhost:8080/getBooks in the direct address bar, and the effect is shown as follows:
2) Using fastjson
fastjson is Alibaba's open-source JSON parser, and also the fastest JSON parser at present. After integration, it needs to provide corresponding HttpMessageConverter to use. Add dependency, as follows:
<!-- Appoint web Dependency module --> <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> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency>
Next, add HttpMessageConverter of fastjson as follows:
@Configuration public class NXFastJsonConfig { @Bean FastJsonHttpMessageConverter fastJsonHttpMessageConverter() { 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); return converter; } }
Then configure a response code in application.properties as follows:
spring.http.encoding.force-response=true
After running, visit http://localhost:8080/getBooks in the direct address bar, and the effect is shown as follows: