1. 程式人生 > >SpringMVC 自定義序列化規則

SpringMVC 自定義序列化規則

文章目錄


本文講解如何如何自定義SpringMVC的序列化規則

使用SpringBoot為例,SpringBoot預設使用Jackson作為序列化工具。通過修改Jackson配置即可自定義序列化規則。

方法1

一般需要為第三方java類實現序列化規則使用,這裡以boolean轉int為例(true/false->1/0),程式碼如下

// 1 編寫自定義序列化類,實現JsonSerializer介面
public class BooleanSerializer extends JsonSerializer<Boolean> {
    @Override
public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException { if (value != null && value) { gen.writeNumber(1); } else { gen.writeNumber(0); } } } // 2 測試 public class Test { @Test public
void globalSerialize() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule simpleModule = new SimpleModule(); BooleanSerializer serializer = new BooleanSerializer(); simpleModule.addSerializer(Boolean.class,serializer); simpleModule.
addSerializer(boolean.class,serializer); objectMapper.registerModule(simpleModule); // 輸出 1 System.out.println(objectMapper.writeValueAsString(true)); } }

在SpringBoot中只要將SimpleModule註冊到容器中,容器會自動配置到Jackson上。全部配置程式碼如下,測試略

@Configuration
public class JacksonConfig {
    /**
     * 自定義boolean型別序列化規則
     */
    static class BooleanSerializer extends JsonSerializer<Boolean> {
        @Override
        public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value != null && value) {
                gen.writeNumber(1);
            } else {
                gen.writeNumber(0);
            }
        }
    }
    @Bean
    public SimpleModule simpleModule() {
        SimpleModule module = new SimpleModule();
        BooleanSerializer serializer = new BooleanSerializer();
        module.addSerializer(Boolean.class, serializer);
        module.addSerializer(boolean.class, serializer);
        return module;
    }

}

方法2

自定義java類使用,以User類為例

@Data
public class User {
	private Integer id;
	private String name;
}
// 1 自定義序列化類實現JsonSerializer介面
public static class UserSerializer extends JsonSerializer<User> {
	// 假設序列化時,為每個欄位增加u字首
	@Override
	public void serialize(User value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
		gen.writeStartObject();
		gen.writeNumberField("uid", value.getId());
		gen.writeStringField("uname", value.getName());
		gen.writeEndObject();
	}
}
// 2 通過@JsonSerialize註解指定序列化類
@JsonSerialize(using = UserSerializer.class)
public static class User {}
// 3 測試
public class Test {
	@Test
	public void serializer() throws IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		User user = new User();
		user.setId(1);
		user.setName("ly");
		String json = objectMapper.writeValueAsString(user);
		// 輸出    {"uid":1,"uname":"ly"}
		System.out.println(json);
	}
}