Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable converting the timezone of a ZonedDateTime field to UTC in spring, only for one field and keep it for all other fields?

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

like image 959
MA1 Avatar asked Oct 27 '25 12:10

MA1


1 Answers

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)
like image 112
Michał Ziober Avatar answered Oct 29 '25 01:10

Michał Ziober



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!