枚举类型在定义应用程序域内有限且明确的值集方面非常有效,有助于避免代码中出现无效状态。
应用场景
以下以一个spring boot 3.3.x 和 mongodb 实现的笔记web应用为例,演示枚举值的序列化和反序列化方法。 我们将定义一个type枚举,表示待办事项的类型:事件和活动。
public enum type { event("event"), activity("activity"); private final string value; type(string value) { this.value = value; } public string getvalue() { return value; } private static final map<string, type> enum_map; static { enum_map = arrays.stream(values()) .collect(collectors.tomap(type::getvalue, t -> t)); } public static type fromstring(string value) { return enum_map.get(value); } }
我们的todo实体类:
public class todo { private string id; private string name; private boolean completed; private type type; // ... getters and setters ... }
我们将探讨以下场景:
- 枚举作为查询参数。
- 枚举作为json请求体的一部分。
- 枚举作为mongodb文档字段。
1. 枚举作为查询参数
此场景只需反序列化,将字符串值转换为枚举。 以下是一个控制器方法片段,用于根据类型读取待办事项,类型作为查询参数传递:
@getmapping("/todos") public collection<todo> read(@requestparam(required = false) type type) { // ... implementation ... }
由于查询参数为字符串,我们需要一个转换器:
public class stringtotypeconverter implements converter<string, type> { @override public type convert(string source) { return type.fromstring(source); } }
在配置类中注册转换器:
@configuration public class webconfig implements webmvcconfigurer { @override public void addformatters(formatterregistry registry) { registry.addconverter(new stringtotypeconverter()); } }
现在,当type用作@requestparam时,stringtotypeconverter将尝试将字符串值转换为枚举。
2. 枚举作为json请求体的一部分
为了正确处理json请求体中的枚举字段,我们需要在type枚举中添加@jsonvalue注解:
(上面的type枚举已包含必要的fromstring和enum_map)
3. 枚举作为mongodb文档字段
为了在mongodb中管理枚举的序列化/反序列化,我们需要使用@valueconverter注解,并将文档字段与一个自定义的propertyvalueconverter类关联:
@document(collection = "todos") public class todo { @id private string id; // ... other fields ... @valueconverter(mongoenumconverter.class) private type type; // ... getters and setters ... } public class mongoenumconverter implements propertyvalueconverter<type, string> { @override public type convert(string source) { return type.fromstring(source); } @override public string write(type value) { return value.getvalue(); } }
mongoenumconverter提供读写方法来管理转换。
总结
本文介绍了在常见web场景中处理枚举序列化/反序列化的几种方法。 spring和jackson库提供了简化此过程的工具。 完整的代码示例可在一个公开的gitlab仓库中找到。(此处省略gitlab仓库链接,因为我没有访问权限)
本文中提供的代码已获得cc0许可。
以上就是在 spring boot web 应用程序中序列化枚举的详细内容,更多请关注代码网其它相关文章!
发表评论