Message converter
In Spring org. Springframework. HTTP. The converter. The HttpMessageConverter specification defines HTTP request and response message conversion specification, We know that SpringMvc can receive and respond to different message forms (json is the most common); If the “valid information” contained in these messages is consistent, different message converters will produce the same conversion result. The differences in parsing details between the various messages are masked in different HttpMessageConverter implementation classes.
FastJson is used as a converter in SpringMVC
FastJson is configured as a converter using message-Case data in SpringMvc
<! Annotations - the default mapping support, org. Springframework. Web. Servlet. MVC) method. The annotation. RequestMappingHandlerMapping - >
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters register-defaults="true">
<! - will Jackson2HttpMessageConverter default formatting output is true -- -- >
<! Fastjson support -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<! Print key with double quotes -->
<value>QuoteFieldNames</value>
<! -- whether to print a null field -->
<! -- <value>WriteMapNullValue</value> -->
<! If the value field is null, the output is 0 instead of NULL.
<value>WriteNullNumberAsZero</value>
<! If the List field is null, the output is [], not null -->
<value>WriteNullListAsEmpty</value>
<! -- If the character type field is null, the output is "", not null -->
<value>WriteNullStringAsEmpty</value>
<! -- Boolean if the field is null, the output is false, not null -->
<value>WriteNullBooleanAsFalse</value>
<! -- null String does not output -->
<value>WriteNullStringAsEmpty</value>
<! -- null String also prints -->
<! -- <value>WriteMapNullValue</value> -->
<! -- Date converter for Date -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<! Content-type = View; content-type = View;
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes" >
<map>
<entry key="json" value="application/json"/>
</map>
</property>
<! Accept header is ignored. Default is false -->
<property name="ignoreAcceptHeader" value="true"/>
<property name="favorPathExtension" value="true"/>
</bean>
Copy the code
Fastjson lightweight attribute conversion
Define the sample object model
Do fastJSON lightweight annotation configuration, for more configuration see github.com/alibaba/fas…
public class ModelTest implements Serializable{
// Use ordinal to specify fields
@JSONField(ordinal = 1)
private Long id;
@JSONField(ordinal = 2)
private String name;
@JSONField(ordinal = 3)
private Integer age;
// Use serialize/deserialize to specify that the field is not serialized
@JSONField(deserialize = false, serialize = false)
private String remark;
// Configure date serialization and antisequence using THE yyyyMMdd date format
@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date crateTime;
// Configure the name to be used for attribute serialization
@JSONField(name = "updateTime", format="yyyy-MM-dd HH:mm:ss")
private Date modifyTime;
@JSONField(ordinal = 0)
private DeleteEnum deleteEnum;
public enum DeleteEnum {
DISABLE(1."Disabled"),
ENABLE(2."Enable");
private int value;
private String depict;
DeleteEnum(int value, String depict) {
this.value = value;
this.depict = depict;
}
public static DeleteEnum findByValue(int value) {
switch (value) {
case 1:
return DISABLE;
case 2:
return ENABLE;
default:
return null; }}}// getter and setter
}
Copy the code
Defining a sample Controller
The sample completes serializing data to the front end and submitting JSON data into an object model
@Controller
@RequestMapping(value = "/test")
public class TestWebController {
private static final Logger LOG = LoggerFactory.getLogger(TestWebController.class);
// Serialize objects to the view
@ResponseBody
@RequestMapping(value = {"/bean/data"}, method = {RequestMethod.GET, RequestMethod.POST})
public Object toBody(a){
ModelTest modelTest = new ModelTest();
modelTest.setAge(11);
modelTest.setCrateTime(new Date());
modelTest.setModifyTime(new Date());
modelTest.setId(1L);
modelTest.setName("Test Fastjson");
modelTest.setRemark("Note");
modelTest.setDeleteEnum(ModelTest.DeleteEnum.ENABLE);
return ImmutableMap.<String, String>builder()
.put("code"."0")
.put("data", JSON.toJSONString(modelTest)).build();
}
// Parse the JSON object into the entity model
@ResponseBody
@RequestMapping(value = {"/bean/put"}, method = {RequestMethod.GET, RequestMethod.POST})
public Object getBody(@RequestBody ModelTest modelTest){
System.out.println(JSON.toJSONString(modelTest));
return ImmutableMap.<String, String>builder()
.put("code"."0")
.put("data"."ok").build(); }}Copy the code
Test objects are serialized to the front end for presentation
@Test
public void fastJSONTest01(a) throws Exception {
MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post("/test/bean/data")
.cookie(new Cookie("token"."F3AF5F1D14F534F677XF3A00E352C")) // Login authorization
.accept(MediaType.parseMediaType("application/json; charset=UTF-8")))
.andExpect(handler().handlerType(TestWebController.class)) // Verify the type of controller executed
.andExpect(status().isOk()) // Verify execution status
.andDo(print()) // Prints the interaction information
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
Copy the code
Execution Result:
{
"code": "0"."data": "{"crateTime":"2016- 12- 2808.: 02: 50","deleteEnum":"ENABLE","updateTime":"2016- 12- 2808.: 02: 50","id": 1,"name":"Test Fastjson","age": 11}"
}
Copy the code
Test the submitted data into the model
@Test
public void fastJSONTest02(a) throws Exception {
ModelTest modelTest = new ModelTest();
modelTest.setAge(11);
modelTest.setCrateTime(new Date());
modelTest.setModifyTime(new Date());
modelTest.setId(1L);
modelTest.setName("Test Fastjson");
modelTest.setRemark("Note");
modelTest.setDeleteEnum(ModelTest.DeleteEnum.ENABLE);
MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post("/test/bean/put")
.content(JSON.toJSONString(modelTest))
.contentType(MediaType.APPLICATION_JSON)
.cookie(new Cookie("token"."F3AF5F1D14F534F677XF3A00E352C")) // Login authorization
.accept(MediaType.parseMediaType("application/json; charset=UTF-8")))
.andExpect(handler().handlerType(TestWebController.class)) // Verify the type of controller executed
.andExpect(status().isOk()) // Verify execution status
.andDo(print()) // Prints the interaction information
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
Copy the code
Performing background printing:
{"crateTime":"The 2016-12-28 08:04:33"."deleteEnum":"ENABLE"."updateTime":"The 2016-12-28 08:04:33"."id":1."name":"Test Fastjson"."age":11}
Copy the code
Enumeration binding processing
In the example, we saw that the serialized enumeration is the name() of the enumeration. If we want to use the implied value of the enumeration for transport mapping, we can do so by passing through a value that is bound to the getter() and setter() methods with the enumeration.
Modify the object model of the example
public class ModelTest implements Serializable{
// Use ordinal to specify fields
@JSONField(ordinal = 1)
private Long id;
@JSONField(ordinal = 2)
private String name;
@JSONField(ordinal = 3)
private Integer age;
// Use serialize/deserialize to specify that the field is not serialized
@JSONField(deserialize = false, serialize = false)
private String remark;
// Configure date serialization and antisequence using THE yyyyMMdd date format
@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date crateTime;
// Configure the name to be used for attribute serialization
@JSONField(name = "updateTime", format="yyyy-MM-dd HH:mm:ss")
private Date modifyTime;
@JSONField(ordinal = 0)
private DeleteEnum deleteEnum;
private int enable;
public enum DeleteEnum {
DISABLE(1."Disabled"),
ENABLE(2."Enable");
private int value;
private String depict;
DeleteEnum(int value, String depict) {
this.value = value;
this.depict = depict;
}
public static DeleteEnum findByValue(int value) {
switch (value) {
case 1:
return DISABLE;
case 2:
return ENABLE;
default:
return null; }}}// Numeric binding enumeration
public int getEnable(a) {
this.deleteEnum = DeleteEnum.findByValue(enable);
return enable;
}
// Numeric binding enumeration
public void setEnable(int enable) {
this.enable = enable;
this.deleteEnum = DeleteEnum.findByValue(enable);
}
// Enumerate mapping values
public DeleteEnum getDeleteEnum(a) {
this.enable = this.deleteEnum.value;
return deleteEnum;
}
// Enumerate mapping values
public void setDeleteEnum(DeleteEnum deleteEnum) {
this.deleteEnum = deleteEnum;
this.enable = this.deleteEnum.value; }}Copy the code
We leave the code for the Controller class and test case in the example unchanged and execute the use case.
Test objects are serialized to the front end for presentation
The execution result
{
"code": "0"."data": "{"crateTime":"2016-12-2808: 12: 52","deleteEnum":"ENABLE","enable": 2,"updateTime":"2016-12-2808: 12: 52","id": 1,"name":"Test Fastjson","age": 11}"
}
Copy the code
Test the submitted data into the model
Performing background printing
{"crateTime":"The 2016-12-28 08:20:17"."deleteEnum":"ENABLE"."enable":2."updateTime":"The 2016-12-28 08:20:17"."id":1."name":"Test Fastjson"."age":11}
Copy the code
Modify the entity object simulated by the use case to test the mapping of values to enumerations.
ModelTest modelTest = new ModelTest();
modelTest.setAge(11);
modelTest.setCrateTime(new Date());
modelTest.setModifyTime(new Date());
modelTest.setId(1L);
modelTest.setName("Test Fastjson");
modelTest.setRemark("Note");
modelTest.setEnable(1);
Copy the code
Background print output:
{"crateTime":"The 2016-12-28 08:21:48"."deleteEnum":"DISABLE"."enable":1."updateTime":"The 2016-12-28 08:21:48"."id":1."name":"Test Fastjson"."age":11}
Copy the code
You can see that the value of enable is automatically mapped to the enumeration type.
Use FastJson to convert objects to JSON
Object is converted to JSON
@Test
public void fastJSONTest03(a) {
ModelTest modelTest = new ModelTest();
modelTest.setAge(11);
modelTest.setCrateTime(new Date());
modelTest.setModifyTime(new Date());
modelTest.setId(1L);
modelTest.setName("Test Fastjson");
modelTest.setRemark("Note");
modelTest.setEnable(1);
System.out.println(JSON.toJSONString(modelTest));
}
Copy the code
Execution Result:
{"crateTime":"The 2016-12-28 08:30:42"."deleteEnum":"DISABLE"."enable":1."updateTime":"The 2016-12-28 08:30:42"."id":1."name":"Test Fastjson"."age":11}
Copy the code
JSON to objects
@Test
public void fastJSONTest04(a) {
String json = "{\n" +
" \"id\": 1,\n" +
" \"deleteEnum\": \"DISABLE\",\n" +
" \"updateTime\": 1482884802549,\n" +
" \"crateTime\": 1482884802549,\n" +
" \"age\": 11,\n" +
\"name\ : \" Test Fastjson\",\n" +
" \"enable\": 1\n" +
"}";
ModelTest modelTest = JSONObject.parseObject(json, ModelTest.class);
System.out.println(modelTest);
System.out.println(modelTest.getName());
}
Copy the code
Execution Result:
ModelTest{id=1, name='test Fastjson', age=11, remark='null', crateTime=Wed Dec 28 08:26:42 CST 2016, modifyTime=Wed Dec 28 08:26:42 CST 2016, deleteEnum=DISABLE, enableTest Fastjson = 1}Copy the code
The output object is printed directly in the example because the toString() method is overridden.