forked from outfoxx/jackson-js
/
JsonDeserialize.ts
executable file
·60 lines (58 loc) · 1.88 KB
/
JsonDeserialize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* @packageDocumentation
* @module Decorators
*/
import {defineMetadata, isNativeCode, makeJacksonDecorator} from '../util';
import {JsonDeserializeDecorator, JsonDeserializeOptions} from '../@types';
/**
* Decorator used to indicates the use of a custom deserializer.
*
* @example
* ```typescript
* class DateSerializer {
* static serializeDate(date): any {
* return {
* year: date.getFullYear(),
* month: date.getMonth() + 1,
* day: date.getDate(),
* formatted: date.toLocaleDateString()
* };
* }
* static deserializeDate(dateObj): Date {
* return new Date(dateObj.formatted);
* }
* }
*
* class Book {
* @JsonProperty() @JsonClassType({type: () => [Number]})
* id: number;
* @JsonProperty() @JsonClassType({type: () => [String]})
* name: string;
*
* @JsonProperty()
* @JsonSerialize({using: DateSerializer.serializeDate})
* @JsonDeserialize({using: DateSerializer.deserializeDate})
* @JsonClassType({type: () => [Date]})
* date: Date;
* }
* ```
*/
export const JsonDeserialize: JsonDeserializeDecorator = makeJacksonDecorator(
(o: JsonDeserializeOptions): JsonDeserializeOptions => ({enabled: true, ...o}),
(options: JsonDeserializeOptions, target, propertyKey, descriptorOrParamIndex) => {
if (descriptorOrParamIndex == null && propertyKey == null) {
defineMetadata('JsonDeserialize', options, target);
return target;
}
if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {
defineMetadata(
'JsonDeserializeParam',
options, (isNativeCode(target.constructor)) ? target : target.constructor,
(propertyKey) ? propertyKey : 'constructor', {
suffix: descriptorOrParamIndex.toString()
});
}
if (propertyKey != null) {
defineMetadata('JsonDeserialize', options, target.constructor, propertyKey);
}
});