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

Groups creation for property #174

Closed AmoryR closed 2 years ago

AmoryR commented 2 years ago

In my API, I have a list of companies and I want to be able to retrieve all of them or retrieve a specific one. So I have two endpoints :

But the Company model contains a lot of data, so I want to create groups for the endpoints.

For example :

Returns

[
    { id: 0, name: "Company1", description: "BlaBla" },
    { id: 1, name: "Company2", description: "BlaBla" },
    { id: 2, name: "Company3", description: "BlaBla" }
]

Returns

{ 
    id: 1, 
    name: "Company2", 
    description: "BlaBla",
    creationDate: "2021-02-02",
    data: []
},

Is this possible with property decorators or do I need to use a custom solution like custom serializer ?

andreas-aeschlimann commented 2 years ago

Of course, this is probably the most basic case scenario. Just use jsonConvert.deserializeArray to deserialize the whole array and jsonConvert.deserializeObject if you have only one object. All you need to do is set your classes up as in the ReadMe.

AmoryR commented 2 years ago

This is what I’ve done in my project but how can I tell, in this scenario I want an array of Company with propertyA and propertyB and in this scenario I just want one Company but with propertyA, propertyB and propertyC ?

I use JsonProperty decorator to serialize/deserialize a property but this one is always serialize/deserialize, can I choose when I want it in my returned object?

Thank you for your response

andreas-aeschlimann commented 2 years ago

Yes, you can use optional properties as well (see docs for ConvertingMode).

AmoryR commented 2 years ago

I found a way to achieve what I wanted by using PropertyConvertingMode :

@JsonProperty("value", Number, PropertyConvertingMode.PASS_NULLABLE)

Thank you Andreas

andreas-aeschlimann commented 2 years ago

Yes, this is the way I would do it. The TypeScript type should then be value: number|null = null.