Issue
I have a spring boot application where the timezone of a ZonedDateTime field gets converted to UTC when a RESTful API receives a request body that has a ZonedDateTime field. How can I make the application keep the original timezone only for one field and convert it to UTC for all other fields?
I know we can disable this for all fields by adding the below line to the properties file, but in my case I don't want to disable it for all fields, I just want to disable it for one field.
spring.jackson.deserialization.ADJUST_DATES_TO_CONTEXT_TIME_ZONE = false
Solution
You can use JsonFormat
annotation:
@JsonFormat(without = {ADJUST_DATES_TO_CONTEXT_TIME_ZONE})
Take a look on below example:
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.File;
import java.io.IOException;
import java.time.ZonedDateTime;
import static com.fasterxml.jackson.annotation.JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE;
public class ZonedJsonApp {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JsonMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.build();
System.out.println(mapper.readValue(jsonFile, ZonedPojo.class));
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
class ZonedPojo {
private ZonedDateTime with;
@JsonFormat(without = {ADJUST_DATES_TO_CONTEXT_TIME_ZONE})
private ZonedDateTime without;
}
Which for below JSON
payload:
{
"with": "2007-12-03T10:15:30+04:00",
"without": "2007-12-03T10:15:30+04:00"
}
Prints:
ZonedPojo(with=2007-12-03T06:15:30Z[UTC], without=2007-12-03T10:15:30+04:00)
Answered By - MichaĆ Ziober