序列化想排除某属性,但反序列化时不排除该属性,能否实现?
- Dominant language
- Swift
- Stars
- 4.3k
- Forks
- 677
- PR merge metrics
- No merged PRs in 30d
Description
我看了文档的『排除指定属性』和『自定义映射和排除』章节:
> 如果在Model中存在因为某些原因不能实现HandyJSON协议的非基本字段,或者不能实现HandyJSONEnum协议的枚举字段,又或者说不希望反序列化影响某个字段,**可以在mapping函数中将它排除**。如果不这么做,可能会出现未定义的行为。
> 和反序列化一样,只要定义mapping和exclude就可以了。**被排除的属性,序列化和反序列化都不再影响到它**。而在mapping中定义的Transformer,同时定义了序列化和反序列的规则,所以只要为属性指明一个Transformer关系就可以了。
但是有时候,我希望在序列化排除掉某个属性,但反序列化时又不排除该属性,举个列子:我有个 Moment 模型,大致如下:
```swift
struct Moment: HandyJSON {
var content: String?
var photoUrls: [String]?
var createdAt: String?
var searchText: String = "" // 有时候我需要加入一些辅助属性,不是 Optional 的
}
```
HandyJSON 中在 mapping 函数排除,会导致无论是反序列化和序列化的时候都会排除掉了。
有些时候,我希望在序列化的时候排序掉 searchText 和 createdAt 这两个属性,以便我传递给服务端;
但是,我同时也希望,当服务端返回 JSON 数据的时候,我在反序列化的时候不要排除 searchText 和 createdAt 这两个属性,HandyJSON 是否能够实现呢?
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the documentation sections on excluding properties and custom mapping, then inspect the HandyJSON mapping behavior used by the Moment example. Define the change around independent serialization and deserialization exclusion, and verify that searchText and createdAt can be omitted when serializing while remaining available during deserialization.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100