Created
May 3, 2020 20:54
-
-
Save pichillilorenzo/f2e3a93736ce7b57c1885de981acd308 to your computer and use it in GitHub Desktop.
@JsonSerialize() and @JsonDeserialize() 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, ObjectMapper, JsonSerialize, JsonDeserialize } from 'jackson-js'; | |
class DateSerializer { | |
static serializeDate(date, context): any { | |
return { | |
year: date.getFullYear(), | |
month: date.getMonth() + 1, | |
day: date.getDate(), | |
formatted: date.toLocaleDateString() | |
}; | |
} | |
static deserializeDate(dateObj, context): Date { | |
return new Date(dateObj.formatted); | |
} | |
} | |
class Book { | |
@JsonProperty() @JsonClassType({type: () => [Number]}) | |
id: number; | |
@JsonProperty() @JsonClassType({type: () => [String]}) | |
name: string; | |
@JsonProperty() @JsonClassType({type: () => [Date]}) | |
@JsonSerialize({using: DateSerializer.serializeDate}) | |
@JsonDeserialize({using: DateSerializer.deserializeDate}) | |
date: Date; | |
constructor(id: number, name: string, @JsonClassType({type: () => [Date]}) date: Date) { | |
this.id = id; | |
this.name = name; | |
this.date = date; | |
} | |
} | |
const book = new Book(1, 'Game Of Thrones', new Date(2012, 11, 4)); | |
const objectMapper = new ObjectMapper(); | |
const jsonData = objectMapper.stringify<Book>(book); | |
console.log(jsonData); | |
// {"id":1,"name":"Game Of Thrones","date":{"year":2012,"month":12,"day":4,"formatted":"4/12/2012"}} | |
const bookParsed = objectMapper.parse<Book>(jsonData, {mainCreator: () => [Book]}); | |
console.log(bookParsed); | |
/* | |
Book { | |
id: 1, | |
name: 'Game Of Thrones', | |
date: 2012-04-11T22:00:00.000Z | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment