/
ObjectMapper.ts
74 lines (67 loc) · 2.48 KB
/
ObjectMapper.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @packageDocumentation
* @module Databind
*/
import {
JsonStringifier
} from '../core/JsonStringifier';
import {
JsonParser
} from '../core/JsonParser';
import {
JsonParserContext,
JsonStringifierContext
} from '../@types';
/**
* ObjectMapper provides functionality for reading and writing JSON.
* It is also highly customizable to work both with different styles of JSON content,
* and to support more advanced Object concepts such as polymorphism and Object identity.
*
* ObjectMapper will use instances of {@link JsonParser} and {@link JsonStringifier}
* for implementing actual reading/writing of JSON.
*/
export class ObjectMapper {
/**
* Default context to use during serialization.
*/
defaultStringifierContext: JsonStringifierContext;
/**
* Default context to use during deserialization.
*/
defaultParserContext: JsonParserContext;
/**
*
* @param defaultStringifierContext - Default context to use during serialization.
* @param defaultParserContext - Default context to use during deserialization.
*/
constructor(
defaultStringifierContext: JsonStringifierContext = JsonStringifier.makeDefaultContext(),
defaultParserContext: JsonParserContext = JsonParser.makeDefaultContext()) {
this.defaultStringifierContext = defaultStringifierContext;
this.defaultParserContext = defaultParserContext;
}
/**
* Method for serializing a JavaScript object or a value to a JSON string.
* Context will be merged using {@link JsonStringifier.mergeContexts} with {@link defaultStringifierContext}.
*
* @param obj - the JavaScript object or value to be serialized.
* @param context - the context to be used during serialization.
*/
stringify<T>(obj: T, context?: JsonStringifierContext): string {
context = JsonStringifier.mergeContexts([this.defaultStringifierContext, context]);
const jsonStringifier = new JsonStringifier<T>();
return jsonStringifier.stringify(obj, context);
}
/**
* Method for deserializing a JSON string into a JavaScript object or value.
* Context will be merged using {@link JsonParser.mergeContexts} with {@link defaultParserContext}.
*
* @param text - the JSON string to be deserialized.
* @param context - the context to be used during deserialization.
*/
parse<T>(text: string, context?: JsonParserContext): T {
context = JsonParser.mergeContexts([this.defaultParserContext, context]);
const jsonParser = new JsonParser<T>();
return jsonParser.parse(text, context);
}
}