Skip to content

Instantly share code, notes, and snippets.

@pichillilorenzo
Created May 3, 2020 20:00
Show Gist options
  • Save pichillilorenzo/cda28e5c0cc889dae9f8e55d99d2c3ba to your computer and use it in GitHub Desktop.
Save pichillilorenzo/cda28e5c0cc889dae9f8e55d99d2c3ba to your computer and use it in GitHub Desktop.
@JsonCreator() example
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