
本文深入探讨了如何使用jackson库实现复杂对象的自定义序列化,特别是针对来自第三方库且不可修改的嵌入式对象。核心内容是利用jackson的converter机制,将领域模型中多个localizedtexts类型的字段,在序列化时统一转换为一个扁平化的translation数组,并详细介绍了实现这一转换所需的中间数据结构、自定义转换器及其集成方法,旨在提供一种灵活且可维护的解决方案。
在现代软件开发中,我们经常需要将领域模型对象序列化为JSON格式,以便存储到文档数据库或通过API传输。然而,当领域对象包含来自第三方库的复杂嵌入式类型时,标准Jackson序列化可能无法满足特定的JSON结构需求。一个典型的场景是,当领域类中包含多个表示多语言文本的字段,且这些字段的类型(例如LocalizedTexts)来自我们无法修改的外部库时。
考虑一个Article领域类,其中包含多个LocalizedTexts类型的字段,如designation、touchCaption、printText和productInformation。LocalizedTexts本身是一个HashMap<Language, String>,其中Language是一个枚举。默认的Jackson序列化会将这些字段分别表示为嵌套的JSON对象:
原始JSON结构示例:
{
"id": "...",
"iNo": 3,
"isValid": true,
"designation": {
"de": "designation3DE ...",
"en": "designation3EN ..."
},
"touchCaption": {
"de": "touchCaption3DE ...",
"en": "touchCaption3EN ..."
},
"productInformation": {
"de": "productInformation3DE ...",
"en": "productInformation3EN ...",
"es": "productInformation3ES ..."
},
"codes": [
"...", "..."
],
// ... 其他字段
}我们的目标是将其转换为一种更扁平、更统一的结构,将所有LocalizedTexts字段的内容提取并合并到一个名为translation的JSON数组中。数组的每个元素应包含一个特定的多语言文本及其对应的语言信息,例如:
目标JSON结构示例:
{
"id": "...",
"iNo": 3,
"isValid": true,
"codes": [
"...", "..."
],
"translation": [
{
"productInformation": "productInformation3DE localized productInformation3 productInformation",
"language": "german"
},
{
"productInformation": "productInformation3EN localized productInformation3 productInformation",
"language": "english"
},
{
"productInformation": "productInformation3ES localized productInformation3 productInformation",
"language": "spanish"
},
{
"touchCaption": "touchCaption3DE localized touchCaption3 touchCaption Bildbeschriftung",
"language": "german"
},
// ... 其他翻译条目
],
// ... 其他字段
}由于LocalizedTexts和Language类来自第三方库,我们无法直接在其上添加Jackson注解。因此,我们需要一种外部化的自定义序列化机制来实现这种复杂的转换。
Jackson提供了多种自定义序列化方式,包括JsonSerializer和Converter。对于涉及复杂对象图转换的场景,Converter通常是更优的选择。
本教程将采用Converter模式,将原始的Article对象转换为一个中间的ArticleWrapper对象,ArticleWrapper将包含我们期望的扁平化translation列表。
为了实现目标JSON结构,我们需要定义两个新的Java类:ArticleWrapper和LanguageAttribute。
ArticleWrapper将作为Article的代理,包含所有不需要特殊处理的字段,以及一个用于承载扁平化多语言数据的translation列表。
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.Singular;
import java.util.List;
import java.util.UUID;
@Builder
@Getter
@Setter
public class ArticleWrapper {
@NonNull
private UUID id;
@JsonProperty("iNo")
private Integer iNo;
private boolean isValid;
@NonNull
private ReferenceArticleGroup articleGroup; // 假设 ReferenceArticleGroup 是一个已有的类
private Integer numberOfDecimalsSalesPrice;
@Singular
private List<String> codes;
private List<LanguageAttribute> translation; // 所有 LocalizedTexts 数据将存储在这里
}LanguageAttribute用于表示translation数组中的每一个元素,它包含一个表示特定字段名和值的映射,以及对应的语言。
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.Map;
// Java 16+ Record 类型,也可以用普通类实现
public record LanguageAttribute(
@JsonAnyGetter // 将Map的内容平铺到JSON对象中,而不是嵌套一个"map"字段
Map<String, String> map,
@JsonProperty("language") // 明确指定JSON字段名为"language"
@JsonSerialize(converter = LanguageConverter.class) // 使用自定义Converter序列化Language枚举
Language language) {}@JsonAnyGetter 注意事项:@JsonAnyGetter 注解用于将Map的键值对直接作为当前JSON对象的属性进行序列化,而不是将Map本身作为一个嵌套对象。例如,如果map是{"productInformation": "..."},则序列化后会直接生成"productInformation": "...",而不是"map": {"productInformation": "..."}。这对于实现动态或扁平化的JSON结构非常有用。
LanguageAttribute中的language字段需要将Language枚举转换为一个特定的字符串(例如,小写形式)。为此,我们需要一个LanguageConverter。
import com.fasterxml.jackson.databind.util.StdConverter;
public class LanguageConverter extends StdConverter<Language, String> {
@Override
public String convert(Language language) {
// 假设 Language 枚举有一个方法可以获取其小写名称,例如 getLangName()
// 如果没有,可以简单使用 language.name().toLowerCase()
return language.getLangName(); // 请替换为实际获取小写语言名称的方法
}
}注意:Language枚举的实际实现未提供。此处假设存在getLangName()方法返回小写的语言名称。如果不存在,您可以根据Language枚举的实际结构进行调整,例如使用language.name().toLowerCase()。
现在,我们来实现核心的ArticleConverter,它负责将Article对象转换为ArticleWrapper。
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.util.StdConverter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
public class ArticleConverter extends StdConverter<Article, ArticleWrapper> {
// 构造函数可以为空,如果不需要特殊初始化
public ArticleConverter() {
}
@Override
public ArticleWrapper convert(Article article) {
// 1. 提取并转换所有 LocalizedTexts 字段到 LanguageAttribute 列表
List<LanguageAttribute> translations = getTranslations(article);
// 2. 构建 ArticleWrapper 对象,包含原始 Article 的非LocalizedTexts字段和新的 translations 列表
return ArticleWrapper.builder()
.id(article.getId())
.iNo(article.getINo())
.isValid(article.isValid())
.articleGroup(article.getArticleGroup())
.numberOfDecimalsSalesPrice(article.getNumberOfDecimalsSalesPrice())
.codes(article.getCodes()) // 假设 codes 字段也是直接复制
.translation(translations)
.build();
}
/**
* 从 Article 对象中提取所有 LocalizedTexts 字段并转换为 LanguageAttribute 列表。
*/
private List<LanguageAttribute> getTranslations(Article article) {
// 使用 Stream API 统一处理所有 LocalizedTexts 字段
return Stream.of(
toLanguageAttribute(article.getDesignation(), "designation"),
toLanguageAttribute(article.getTouchCaption(), "touchCaption"),
toLanguageAttribute(article.getPrintText(), "printText"),
toLanguageAttribute(article.getProductInformation(), "productInformation")
)
.flatMap(Function.identity()) // 将 Stream<Stream<LanguageAttribute>> 扁平化为 Stream<LanguageAttribute>
.toList(); // 收集结果到 List
}
/**
* 将单个 LocalizedTexts 对象转换为 LanguageAttribute 的 Stream。
* 每个 LocalizedTexts 条目 (Language -> String) 对应一个 LanguageAttribute。
*/
private Stream<LanguageAttribute> toLanguageAttribute(LocalizedTexts texts, String attribute) {
if (texts == null || texts.isEmpty()) {
return Stream.empty(); // 处理空或null的 LocalizedTexts
}
return texts.entrySet().stream()
.map(entry -> new LanguageAttribute(
Map.of(attribute, entry.getValue()), // 创建单键值对Map
entry.getKey())
);
}
}最后一步是将ArticleConverter注册到Article类上,让Jackson知道在序列化Article对象时应该使用这个自定义转换器。
在Article类定义上添加@JsonSerialize注解:
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
// ... 其他导入
@Value
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@SuperBuilder(toBuilder = true)
@JsonDeserialize(builder = Article.ArticleBuilderImpl.class)
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@JsonSerialize(converter = ArticleConverter.class) // <-- 添加此行
public class Article extends AbstractEntityBase {
@NonNull
UUID id;
@JsonProperty("iNo")
Integer iNo;
boolean isValid;
@NonNull
LocalizedTexts designation;
@NonNull
ReferenceArticleGroup articleGroup;
Integer numberOfDecimalsSalesPrice;
LocalizedTexts touchCaption;
LocalizedTexts printText;
LocalizedTexts productInformation;
@Singular
List<String> codes;
// ...
}现在,当使用ObjectMapper序列化Article对象时,Jackson会自动调用ArticleConverter将其转换为ArticleWrapper,然后再序列化ArticleWrapper,从而生成我们期望的扁平化JSON结构。
为了演示上述实现,您可以使用如下代码进行序列化:
import com.fasterxml.jackson.databind.ObjectMapper;
// ... 导入 Article, LocalizedTexts, Language 等类
public class SerializationDemo {
public static void main(String[] args) throws JsonProcessingException {
// 假设 Article, LocalizedTexts, Language, ReferenceArticleGroup 等类已定义
// 并已使用 @JsonSerialize(converter = ArticleConverter.class) 注解 Article 类
// 创建一个 ObjectMapper 实例
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 美化输出
// 构造一个 LocalizedTexts 实例
LocalizedTexts designation = new LocalizedTexts();
designation.put(Language.DE, "designation3DE localized designation3 designation");
designation.put(Language.EN, "designation3EN localized designation3 designation");
LocalizedTexts productInformation = new LocalizedTexts();
productInformation.put(Language.DE, "productInformation3DE localized productInformation3 productInformation");
productInformation.put(Language.EN, "productInformation3EN localized productInformation3 productInformation");
productInformation.put(Language.ES, "productInformation3ES localized productInformation3 productInformation");
// 构造一个 Article 实例
Article article = Article.builder()
.id(UUID.fromString("57bf6daf-4993-4c55-9b19-db6b3d5c9527"))
.iNo(3)
.isValid(true)
.designation(designation)
.productInformation(productInformation)
.articleGroup(new ReferenceArticleGroup("8f6627b8-31d4-4e44-9374-6069571489f7", "ArticleGroup")) // 假设构造函数
.numberOfDecimalsSalesPrice(2)
.code("1231231231234")
.code("2345678901234")
.build();
// 执行序列化
String jsonOutput = objectMapper.writeValueAsString(article);
System.out.println(jsonOutput);
}
}本教程主要聚焦于序列化过程。如果需要将目标JSON结构反序列化回原始的Article对象,则需要实现一个对应的JsonDeserializer或Converter。
反序列化通常是序列化的逆过程,涉及从扁平化结构重建嵌套结构。这会要求解析translation数组中的每个元素,根据字段名(如productInformation、designation)和语言信息,将值重新填充到对应的LocalizedTexts对象中。
通过利用Jackson的Converter机制,我们成功地解决了对来自第三方库且不可修改的嵌入式对象进行复杂自定义序列化的挑战。这种方法的核心优势在于:
这种模式在处理遗留系统、集成外部API或满足特定数据存储格式要求时,提供了一种强大且优雅的解决方案。
以上就是Jackson自定义序列化:处理外部库嵌入对象并扁平化多语言字段的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号