Created
May 3, 2020 20:00
-
-
Save pichillilorenzo/cda28e5c0cc889dae9f8e55d99d2c3ba to your computer and use it in GitHub Desktop.
@JsonCreator() example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { JsonClassType, JsonProperty, JsonCreator, ObjectMapper } from 'jackson-js'; | |
class Employee { | |
@JsonProperty() @JsonClassType({type: () => [Number]}) | |
id: number; | |
@JsonProperty() @JsonClassType({type: () => [String]}) | |
name: string; | |
@JsonProperty() @JsonClassType({type: () => [String]}) | |
department: string; | |
constructor(id: number, name: string, department: string) { | |
this.id = id; | |
this.name = name; | |
this.department = department; | |
} | |
@JsonCreator() | |
static toEmployee(id: number, | |
@JsonProperty({value: 'empName'}) name: string, | |
@JsonProperty({value: 'empDept'}) department: string): Employee { | |
return new Employee(id, name, department); | |
} | |
} | |
const jsonData = '{"id": 1,"empName": "Chris","empDept": "Admin"}'; | |
const objectMapper = new ObjectMapper(); | |
const employee = objectMapper.parse<Employee>(jsonData, {mainCreator: () => [Employee]}); | |
console.log(employee); | |
/* | |
Employee { | |
id: 1, | |
name: 'Chris', | |
department: 'Admin' | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment