You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DynamoDB中存储的枚举列表转换为字符串形式

解决DynamoDB存储的枚举列表从整数转字符串的问题

我遇到一个问题:存在DynamoDB中的对象里,有个枚举列表属性存储的是整数值,我想把它转换成对应的枚举字符串输出。我尝试了两种方式配置JsonStringEnumConverter,但没达到预期效果。

我尝试的配置

  1. 给枚举类添加JsonConverter特性:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Category
{
    [EnumMember(Value = "Air")]
    Air = 1,

    [EnumMember(Value = "Car")]
    Car = 2,

    [EnumMember(Value = "Hotel")]
    Hotel = 3,

    [EnumMember(Value = "Cruise")]
    Cruise = 4
}
  1. 在Mvc启动配置中添加转换器:
.AddMvc().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.IgnoreNullValues = true;
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

当前数据格式

"ContentAttributes": null,
"IsOrderFees": false,
"Categories": [
    4,
    1,
    2,
    3
]

期望转换后的格式

"ContentAttributes": null,
"IsOrderFees": false,
"Categories": [
    "Cruise",
    "Air",
    "Car",
    "Hotel"
]

解决方案

情况1:调整System.Text.Json转换器配置

如果是API返回时需要把枚举列表转成字符串,首先确保实体类的Categories属性类型是List<Category>而非List<int>。然后修改Mvc的Json配置,让转换器优先使用EnumMember指定的名称,并且禁用整数值的序列化:

.AddMvc().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.IgnoreNullValues = true;
    // 传入null使用EnumMember的命名,设置allowIntegerValues为false强制输出字符串
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(null, allowIntegerValues: false));
});

注意:确保JsonConverter特性引用的是System.Text.Json.Serialization.JsonConverter,而非Newtonsoft.Json的同名特性,避免序列化工具混用导致不生效。

情况2:适配DynamoDB的序列化逻辑

如果问题出在DynamoDB读写时的转换(比如从DB读出来还是整数列表),需要针对AWS DynamoDB SDK自定义属性转换器:

  1. 实现IPropertyConverter接口:
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;

public class CategoryListConverter : IPropertyConverter
{
    // 从DynamoDB条目转成List<Category>
    public object ConvertFromEntry(DynamoDBEntry entry)
    {
        var primitiveList = entry as PrimitiveList;
        if (primitiveList == null) return null;
        
        return primitiveList.Select(p => (Category)p.AsInt()).ToList();
    }

    // 把List<Category>转成DynamoDB存储的整数列表
    public DynamoDBEntry ConvertToEntry(object value)
    {
        var categories = value as List<Category>;
        if (categories == null) return null;
        
        return new PrimitiveList
        {
            Elements = categories.Select(c => new Primitive((int)c)).ToList()
        };
    }
}
  1. 在实体类的Categories属性上指定转换器:
[DynamoDBProperty(Converter = typeof(CategoryListConverter))]
public List<Category> Categories { get; set; }

这样从DynamoDB读取数据时,整数列表会自动转成List<Category>,再配合Mvc的Json转换器,就能输出对应的枚举字符串了。

内容的提问来源于stack exchange,提问作者Mysterious288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 00:33:36