Json 序列化与对象映射
模块位于 src/core/Json。成功响应返回前,Application 会调用 ObjectMapper.writeValue(result),再包进 ResponseData。
全局配置(可选)
不注册也可用默认配置。需要改全局时:
ts
import Json from '@/core/Json'
Application.registry(
Json({
dateFormat: 'yyyy-MM-dd HH:mm:ss', // 默认
deep: true,
include: JsonIncludeType.ALWAYS, // 默认不过滤空值
})
)装饰器
| 装饰器 | 作用 |
|---|---|
@JsonFormat({ pattern, timezone? }) | 格式化 Date;timezone 为小时偏移如 8 |
@JsonInclude(type) | 序列化时省略策略(类或字段) |
@JsonProperty() | 登记字段,供 convert 发现属性 |
JsonIncludeType:ALWAYS / NON_NULL / NON_EMPTY / NON_DEFAULT。
优先级:字段 > 类 > 全局。
实体示例(business/entity/user.ts):
ts
@JsonInclude(JsonIncludeType.NON_NULL)
export default class UserEntity {
@JsonFormat({ pattern: 'yyyy-MM-dd HH:mm:ss' })
createTime?: Date
@JsonFormat({ pattern: 'yyyy-MM-dd HH:mm:ss' })
updateTime?: Date
}raw: true 的接口(文件下载等)不走 ObjectMapper。
convert / copyProperties / pick
用于 DTO 投影、字段拷贝:
ts
import { convert, copyProperties, pick } from '@/core/Application'
// 按目标类字段映射(目标类字段上需有装饰器,或显式传 fields)
const data = convert(dto, CreateUserDTO)
await this.insert({
id: nextId(),
...convert(data, ['username', 'nickName', 'avatar', 'email', 'phone']),
})
copyProperties(source, target, { ignoreUndefined: true })
const vo = pick(row, ['id', 'username'])选项:ignoreUndefined / ignoreNull(默认 false)。
ObjectMapper API
ts
ObjectMapper.configure({ dateFormat: 'yyyy-MM-dd' })
ObjectMapper.writeValue(data)
ObjectMapper.registerTypeHandler(SomeType, (v) => /* ... */)