
本教程详细介绍了如何使用jackson库对来自第三方库的嵌入式对象进行自定义序列化,特别是将复杂的嵌套结构扁平化为列表。通过引入jackson的`converter`机制和辅助包装类,即使无法修改原始类,也能灵活地将`localizedtexts`等类型转换为统一的`translation`列表格式,满足特定的json输出需求,从而实现对不可变第三方对象的高级序列化控制。
在Java开发中,我们经常需要将领域对象序列化为JSON格式存储或传输。当领域对象中包含来自第三方库的复杂类型,且这些类型无法直接修改时,如何实现自定义的JSON序列化以满足特定需求,就成了一个常见的挑战。本文将以一个具体案例为例,详细讲解如何利用Jackson的Converter机制,将嵌入的LocalizedTexts对象扁平化为统一的翻译列表。
假设我们有一个Article领域类,其中包含多个LocalizedTexts类型的属性,如designation、touchCaption、printText和productInformation。LocalizedTexts本身是一个继承自HashMap<Language, String>的类,Language是一个枚举类型。这些类都来自第三方库,我们无权修改其源代码。
原始领域类示例:
@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)
public class Article extends AbstractEntityBase {
@NonNull
UUID id;
@JsonProperty("iNo")
Integer iNo;
boolean isValid;
@NonNull
LocalizedTexts designation; // LocalizedTexts类型
@NonNull
ReferenceArticleGroup articleGroup;
Integer numberOfDecimalsSalesPrice;
LocalizedTexts touchCaption; // LocalizedTexts类型
LocalizedTexts printText; // LocalizedTexts类型
LocalizedTexts productInformation; // LocalizedTexts类型
@Singular
List<String> codes;
// ... 其他属性
}
@Builder(builderMethodName = "internalBuilder")
public class LocalizedTexts extends HashMap<Language, String> implements EntityBase {
public LocalizedTexts() {}
public LocalizedTexts(Map map) {
putAll(map);
}
}
public enum Language {
AA("aa"), AB("ab"), AE("ae"), AF("af"), AK("ak"); // 简化示例
private final String langName;
Language(String langName) {
this.langName = langName;
}
public String getLangName() { // 假设存在此方法
return langName;
}
}Jackson默认序列化输出:
默认情况下,Jackson会将LocalizedTexts序列化为一个嵌套的JSON对象,键为Language枚举的名称(或其toString()结果),值为对应的字符串。
{
"id": "...",
"iNo": 3,
"isValid": true,
"designation": {
"de": "designation3DE ...",
"en": "designation3EN ..."
},
"articleGroup": { /* ... */ },
"touchCaption": {
"de": "touchCaption3DE ...",
"en": "touchCaption3EN ..."
},
"printText": { /* ... */ },
"productInformation": {
"de": "productInformation3DE ...",
"en": "productInformation3EN ...",
"es": "productInformation3ES ..."
},
"codes": [ /* ... */ ]
}期望的扁平化JSON结构:
我们的目标是将所有LocalizedTexts属性中的本地化文本条目提取出来,统一放入一个名为translation的扁平数组中。数组的每个元素都是一个对象,包含一个动态键(原属性名,如productInformation)及其值,以及对应的language。
{
"id": "...",
"iNo": 3,
"isValid": true,
"articleGroup": { /* ... */ },
"codes": [ /* ... */ ],
"translation": [
{
"productInformation": "productInformation3DE localized productInformation3 productInformation",
"language": "german"
},
{
"productInformation": "productInformation3EN localized productInformation3 productInformation",
"language": "english"
},
// ... 其他 productInformation 翻译
{
"touchCaption": "touchCaption3DE localized touchCaption3 touchCaption Bildbeschriftung",
"language": "german"
},
// ... 其他 touchCaption 翻译
{
"designation": "designation3DE localized designation3 designation",
"language": "german"
}
// ... 其他 translation 条目
]
}面对不能修改原始类但需要彻底改变其序列化行为的需求,Jackson提供了多种机制。其中,Converter是一种非常强大且灵活的选择。
在本例中,我们需要将Article对象转换为一个完全不同的结构(ArticleWrapper),其中包含扁平化的LocalizedTexts数据。因此,Converter是比JsonSerializer更合适的选择。
为了实现期望的JSON结构,我们需要定义两个辅助类:ArticleWrapper和LanguageAttribute。
ArticleWrapper将作为Article在序列化过程中的中间表示。它包含了Article中所有非LocalizedTexts的字段,以及一个用于存放扁平化翻译数据的translation列表。
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
import lombok.Singular; // 如果Article中使用了@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是Article中的一个类型
private Integer numberOfDecimalsSalesPrice;
@Singular
private List<String> codes;
// 所有LocalizedTexts的数据将被存储在这里
private List<LanguageAttribute> translation;
}LanguageAttribute用于表示translation列表中每一个元素,它包含一个动态键值对(如"productInformation": "...")和对应的语言。我们使用Java 16 record来定义它,也可以使用普通类。
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.Map;
public record LanguageAttribute(
@JsonAnyGetter // 将Map中的键值对直接作为当前对象的属性输出
Map<String, String> map,
@JsonProperty
@JsonSerialize(converter = LanguageConverter.class) // 使用LanguageConverter序列化Language枚举
Language language) {}@JsonAnyGetter注解说明:@JsonAnyGetter注解被放置在Map<String, String> map字段上。它的作用是告诉Jackson,在序列化时,不要将map字段本身作为一个嵌套对象输出,而是将其内部的所有键值对“展开”到当前对象的顶层。这样,如果map包含{"productInformation": "value"},那么JSON输出将直接是"productInformation": "value",而不是"map": {"productInformation": "value"}。
@JsonUnwrapped与@JsonAnyGetter:@JsonUnwrapped也可以用于将嵌套对象展开,但它存在一个已知问题(FasterXML/jackson-databind#171),即在某些情况下,当有多个@JsonUnwrapped字段时,可能会导致意外行为。因此,对于这种动态键的需求,@JsonAnyGetter通常是更稳健的选择。
为了将Language枚举序列化为小写的语言名称字符串(例如"german"而不是"GERMAN"或"DE"),我们需要一个简单的Converter。
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枚举中获取名称的方法
}
}现在,我们将实现核心的ArticleConverter,它继承自StdConverter<Article, ArticleWrapper>。这个Converter的convert方法将负责把Article对象转换为ArticleWrapper对象,并在此过程中完成LocalizedTexts的扁平化。
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.util.StdConverter;
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属性
List<LanguageAttribute> translations = getTranslations(article);
// 2. 构建ArticleWrapper对象,复制Article的其他属性
return ArticleWrapper.builder()
.id(article.getId())
.iNo(article.getINo()) // 假设getINo()是获取iNo属性的方法
.isValid(article.isValid())
.articleGroup(article.getArticleGroup())
.numberOfDecimalsSalesPrice(article.getNumberOfDecimalsSalesPrice())
.codes(article.getCodes()) // 假设getCodes()是获取codes属性的方法
.translation(translations) // 将扁平化的翻译列表设置到translation字段
.build();
}
/**
* 从Article对象中提取所有LocalizedTexts属性,并将其转换为LanguageAttribute列表。
* @param article Article对象
* @return 扁平化的LanguageAttribute列表
*/
private List<LanguageAttribute> getTranslations(Article article) {
// 使用Stream.of将所有LocalizedTexts属性(及其对应的JSON键名)组合成一个Stream
return Stream.of(
toLanguageAttribute(article.getDesignation(), "designation"),
toLanguageAttribute(article.getTouchCaption(), "touchCaption"),
toLanguageAttribute(article.getPrintText(), "printText"),
toLanguageAttribute(article.getProductInformation(), "productInformation")
)
// flatMap将每个属性转换成的Stream<LanguageAttribute>合并成一个单一的Stream
.flatMap(Function.identity())
.toList(); // 收集为List
}
/**
* 将单个LocalizedTexts对象转换为Stream<LanguageAttribute>。
* @param texts LocalizedTexts对象
* @param attributeName 该LocalizedTexts对应的JSON属性名
* @return 包含LanguageAttribute的Stream
*/
private Stream<LanguageAttribute> toLanguageAttribute(LocalizedTexts texts, String attributeName) {
if (texts == null || texts.isEmpty()) {
return Stream.empty(); // 如果LocalizedTexts为空,则返回空Stream
}
return texts.entrySet().stream()
.map(entry -> new LanguageAttribute(
Map.of(attributeName, entry.getValue()), // 动态键值对
entry.getKey()) // 对应的语言
);
}
}ArticleConverter实现解析:
要将自定义的ArticleConverter应用于Article类,只需在Article类上使用@JsonSerialize注解,并指定converter属性:
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
// ... 其他注解
@JsonSerialize(converter = ArticleConverter.class) // 应用自定义Converter
public class Article extends AbstractEntityBase {
// ... 类定义
}现在,当你使用Jackson ObjectMapper序列化Article对象时,Jackson会自动调用ArticleConverter,将Article转换为ArticleWrapper,然后序列化ArticleWrapper,从而生成我们期望的扁平化JSON结构。
示例:使用ObjectMapper进行序列化
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class SerializationExample {
public static void main(String[] args) throws JsonProcessingException {
// 创建一个示例Article对象
LocalizedTexts designation = new LocalizedTexts(Map.of(
Language.DE, "designation3DE localized designation3 designation",
Language.EN, "designation3EN localized designation3 designation"
));
LocalizedTexts productInformation = new LocalizedTexts(Map.of(
Language.DE, "productInformation3DE localized productInformation3 productInformation",
Language.EN, "productInformation3EN localized productInformation3 productInformation",
Language.ES, "productInformation3ES localized productInformation3 productInformation"
));
Article article = Article.builder()
.id(UUID.randomUUID())
.iNo(3)
.isValid(true)
.designation(designation)
.productInformation(productInformation)
// ... 设置其他属性
.build();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 美化输出
String json = objectMapper.writeValueAsString(article);
System.out.println(json);
}
}本教程主要关注自定义序列化。如果需要将上述扁平化JSON反序列化回原始的Article对象,也需要实现一个自定义的Converter(或JsonDeserializer)。
反序列化通常比序列化更复杂,因为它涉及从扁平结构中识别并重构原始的嵌套对象。这需要仔细地遍历translation列表,根据动态键名将数据分配给正确的LocalizedTexts属性。
通过上述方法,我们可以灵活地控制Jackson的序列化行为,即使面对来自不可修改的第三方库的复杂对象,也能轻松实现自定义的JSON输出格式。
以上就是Jackson高级序列化:扁平化外部库嵌入对象的实践指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号