appvision-gmbh / json2typescript

Map JSON to a TypeScript class with secure type checking!
https://www.npmjs.com/package/json2typescript
MIT License
278 stars 55 forks source link

how to set null property to default value? #196

Closed kongmengfei closed 1 year ago

kongmengfei commented 1 year ago

I want to deserialize objects and set the default value when the property value is null.

image

below is my code:

image

image

Can you help me? the demo use js code but my project is ts.

Thanks

andreas-aeschlimann commented 1 year ago

Hello, there are multiple options you can use in the @JsonProperty decorator as third parameter.

Please refer to the docs: https://github.com/appvision-gmbh/json2typescript#third-parameter-optional-convertingmode for property setting https://github.com/appvision-gmbh/json2typescript#property-converting-mode for global setting

Most likely, you want PropertyConvertingMode.IGNORE_NULLABLE. This means that the mapper is not applied if the property is missing, undefined or null; the property is not added to the result.

When deserializing, the default TypeScript class property value will survive when it was NULL or missing in the JSON.