Code generation to initialise by default to empty list instead of null
Asked Answered
H

3

8

Does Swagger code generation tool have an option for selecting whether the generated classes should have Lists, Maps etc. defaulted to null or empty?

Previously, the default was empty, for example private List<String> names = new List<String>.

At the moment the default is null, i.e. private List<String> names = null

The change was done in April 2017 and based on what I understand from the changes made there is no option for selecting which to use, it's always defaulted to null from that point onwards.

The discussion contains reasons why this is better and I have nothing against that. But I have a legacy app that have used some form of (Swagger) generated sources with little modifications and I'm trying to get rid of these and use swagger generated model only. The problem is that the code is originally written in a manner that there can be no null values and thus null checks are not done.

So what can be done? Use previous version of Swagger codegen?

The API is not in my control and thus yaml modification is not an option (if that would even provide help).

Hawkshaw answered 31/7, 2018 at 13:57 Comment(0)
H
3

I solved this issue as I was speculating in the question and downgraded the codegen cli version to 2.2.2, which is AFAIK the last version that creates lists and maps empty instead of null.

Hawkshaw answered 4/8, 2018 at 10:54 Comment(2)
It is a pity having to downgrade. But I do not find any other alternative.Jadeite
Is the pity state continues in 2021? "NullPointerException"Telestich
A
2

Based on a comment [Java] How can we set List and Map to null by default in models? you'd need to edit any mustache template files for java (most likely pojo.mustache) and change the way lists/maps are instantiated.

Aelber answered 3/8, 2018 at 18:33 Comment(1)
Thanks for the suggestion. I already went down the road of downgrading the codegen cli version.Hawkshaw
P
2

I was able to do this in my specification file: default: []

Pedigo answered 3/5, 2022 at 9:18 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Rickey
To add more precision, in OpenAPI/Swagger specification YAML file. You can add default parameter (See Default Parameter Values here: swagger.io/docs/specification/describing-parameters) But keep in mind that this will only work when the field is also required: trueMccraw

© 2022 - 2024 — McMap. All rights reserved.