首页 > Java > java教程 > 正文

Jackson自定义序列化:处理外部库嵌入对象并扁平化多语言字段

心靈之曲
发布: 2025-11-22 15:16:02
原创
932人浏览过

Jackson自定义序列化:处理外部库嵌入对象并扁平化多语言字段

本文深入探讨了如何使用jackson库实现复杂对象的自定义序列化,特别是针对来自第三方库且不可修改的嵌入式对象。核心内容是利用jackson的converter机制,将领域模型中多个localizedtexts类型的字段,在序列化时统一转换为一个扁平化的translation数组,并详细介绍了实现这一转换所需的中间数据结构、自定义转换器及其集成方法,旨在提供一种灵活且可维护的解决方案。

1. 引言:自定义序列化的需求背景

在现代软件开发中,我们经常需要将领域模型对象序列化为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注解。因此,我们需要一种外部化的自定义序列化机制来实现这种复杂的转换。

2. Jackson Converter 机制详解

Jackson提供了多种自定义序列化方式,包括JsonSerializer和Converter。对于涉及复杂对象图转换的场景,Converter通常是更优的选择。

  • JsonSerializer: 直接控制JSON生成器(JsonGenerator),以低级别的方式编写JSON。这在需要对单个字段进行微调时非常有用,但对于涉及整个对象结构大规模转换时,代码会变得复杂且难以维护。
  • Converter: Converter的目的是将一个类型(源类型)转换为另一个Jackson能够更方便序列化的类型(目标类型)。它充当了Jackson序列化过程中的一个“中间件”,在实际序列化发生之前对对象进行预处理。这种方式使得转换逻辑与实际的JSON生成逻辑分离,提高了代码的可读性和可维护性。

本教程将采用Converter模式,将原始的Article对象转换为一个中间的ArticleWrapper对象,ArticleWrapper将包含我们期望的扁平化translation列表。

3. 定义中间数据结构

为了实现目标JSON结构,我们需要定义两个新的Java类:ArticleWrapper和LanguageAttribute。

3.1 ArticleWrapper:序列化的目标容器

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 数据将存储在这里
}
登录后复制

3.2 LanguageAttribute:单个翻译条目

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结构非常有用。

LobeHub
LobeHub

LobeChat brings you the best user experience of ChatGPT, OLLaMA, Gemini, Claude

LobeHub 201
查看详情 LobeHub

4. 实现 Language 枚举的自定义转换

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()。

5. 实现 Article 对象的自定义转换器

现在,我们来实现核心的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())
            );
    }
}
登录后复制

6. 集成 Converter 到 Article 类

最后一步是将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结构。

7. 序列化示例

为了演示上述实现,您可以使用如下代码进行序列化:

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);
    }
}
登录后复制

8. 反序列化(逆向转换)的考虑

本教程主要聚焦于序列化过程。如果需要将目标JSON结构反序列化回原始的Article对象,则需要实现一个对应的JsonDeserializer或Converter。

  • 使用 JsonDeserializer: 您可以为Article类实现一个StdDeserializer,手动解析JSON中的translation数组,并将其内容填充回Article对象的LocalizedTexts字段。
  • 使用 Converter 进行反序列化: 可以在@JsonDeserialize注解中使用converter属性,指向一个从ArticleWrapper到Article的Converter。这要求JSON首先被反序列化为ArticleWrapper,然后Converter将ArticleWrapper转换为Article。这种方法通常需要一个自定义的JsonDeserializer来将JSON反序列化为ArticleWrapper,因为Jackson默认可能无法直接将扁平化的translation数组映射到ArticleWrapper的结构。

反序列化通常是序列化的逆过程,涉及从扁平化结构重建嵌套结构。这会要求解析translation数组中的每个元素,根据字段名(如productInformation、designation)和语言信息,将值重新填充到对应的LocalizedTexts对象中。

9. 总结

通过利用Jackson的Converter机制,我们成功地解决了对来自第三方库且不可修改的嵌入式对象进行复杂自定义序列化的挑战。这种方法的核心优势在于:

  • 职责分离: 转换逻辑(从Article到ArticleWrapper)与实际的JSON生成逻辑分离。
  • 可维护性: 中间对象ArticleWrapper和LanguageAttribute使得目标JSON结构更加清晰,转换逻辑也更易于理解和修改。
  • 灵活性: Converter模式允许在序列化前对对象进行任意复杂的转换,而无需修改原始领域模型或第三方库代码。

这种模式在处理遗留系统、集成外部API或满足特定数据存储格式要求时,提供了一种强大且优雅的解决方案。

以上就是Jackson自定义序列化:处理外部库嵌入对象并扁平化多语言字段的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号