Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ ObjectMapper 注册逻辑优化 #300

Merged
merged 1 commit into from
Apr 11, 2024

Conversation

evil0th
Copy link
Contributor

@evil0th evil0th commented Apr 11, 2024

        @Bean
	@ConditionalOnClass(ObjectMapper.class)
	@ConditionalOnMissingBean(ObjectMapper.class)
	public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
		// org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration.JacksonObjectMapperConfiguration
		ObjectMapper objectMapper = builder.createXmlMapper(false).build();

		// 对于空对象的序列化不抛异常
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		// 序列化时忽略未知属性
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		// NULL值修改
		objectMapper.setSerializerProvider(new NullSerializerProvider());
		// 有特殊需要转义字符, 不报错
		objectMapper.enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature());
		// 更新 JsonUtils 中的 ObjectMapper,保持容器和工具类中的 ObjectMapper 对象一致
		JacksonJsonToolAdapter.setMapper(objectMapper);

		return objectMapper;
	}

其中序列化配置使用 spring boot 原生 jackson 配置即可实现,不应在这里重复处理,会导致配置失效。
可以在项目的配置文件中进行配置。
等效配置如下:

spring:
  jackson:
    serialization:
      fail-on-empty-beans: false
    deserialization:
      fail-on-unknown-properties: false
    parser:
      allow-unquoted-control-chars: true

另外 NullSerializerProvider 中针对不同类型的控制应可以自定义开关。
新配置如下:

ballcat:
  jackson:
    serialization:
      write-null-string-values-as-quotes: true # null string序列化为""
      write-null-array-values-as-brackets: true # null array序列化为[]
      write-null-map-values-as-braces: true # null map序列化为{}

@Hccake Hccake merged commit 5468ef4 into ballcat-projects:master Apr 11, 2024
0 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants