'Can we generate @JsonFormat on model variable using swagger-generater?
I have a variable in yml file
startDate:
type:string
format:date
I'm using swagger-generater to generate java code from yml.
It's generating a startDate variable as below
@JsonProperty("startDate")
private LocalDate startDate = null;
But I need as below
@JsonProperty("startDate")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate startDate = null;
Can someone help me on this?
Solution 1:[1]
The problem here is you are trying to serialize a Java 8 LocalDate using @JsonFormat without using right jackson module/dependency. If you have a look the annotation doc, it says;
Common uses include choosing between alternate representations -- for example, whether Date is to be serialized as number (Java timestamp) or String (such as ISO-8601 compatible time value) -- as well as configuring exact details with pattern() property.
There's no proper documentation in the swagger codegen project about how to specify language specific configuration options, I have only seen those config options in the following ticket;
https://github.com/swagger-api/swagger-codegen/issues/7795
As per the that issue, you could force Swagger codegen to use java8 dateLibrary.
Solution 2:[2]
you can try desarialize with this way:
ObjectMapper objectMapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setDateFormat(df);
JSONObject jsonObject=new JSONObject(new Oferta().fechaInicio(new Date()));
String json="";
try{
json=objectMapper.writeValueAsString(new Oferta().fechaInicio(new Date()).fechaAceptacion("15/554/20"));
jsonObject=new JSONObject(json);
}catch (Exception e){
}
public class Oferta {
@JsonProperty("fechaInicio")
private Date fechaInicio = null;
@JsonProperty("fechaAceptacion")
private String fechaAceptacion = null;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jhon Larru |
