user3435425
user3435425

Reputation: 322

Spring JSON converter. How to bind different types

I have an ajax call with data: "{"timeLeft": 12:33, "cheked": true}". On the clienside timeleft format: HH:MM, but on the serverside we need to convert it to milliseconds (Long). How to do that with MappingJackson2HttpMessageConverter? In Spring after submitting form we can use PropertyEditors. Is there something similar for json data in Jackson Converters? Thanks

Upvotes: 2

Views: 3084

Answers (2)

wassgren
wassgren

Reputation: 19211

The MappingJackson2HttpMessageConverter uses Jackson's ObjectMapper to deserialize from JSON to Pojos (or from JSON to Maps/JsonNodes). So, one approach is to create a POJO that is to be the deserialized object.

If the expected time value is truly "HH:MM" where "HH" actually means a "Hour of Day (0-23)" and "MM" means "Minute of Hour (0-59)" then the following approach can be used.

Add a custom @JsonCreator to your backing POJO:

public class TimeLeftPojo {
    // The time pattern
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

    // The checked property
    private final boolean checked;

    // The parsed time
    private final LocalTime timeLeft;

    // A creator that takes the string "HH:mm" as arg
    @JsonCreator
    public static TimeLeftPojo of(
            @JsonProperty("timeLeft") String timeLeft, 
            @JsonProperty("checked") boolean checked) {

        return new TimeLeftPojo(
                LocalTime.parse(timeLeft, formatter), checked);
    }

    public TimeLeftPojo(final LocalTime timeLeft, final boolean checked) {
        this.timeLeft = timeLeft;
        this.checked = checked;
    }

    public LocalTime getTimeLeft() {
        return timeLeft;
    }

    public long toMillisecondOfDay() {
        return getTimeLeft().toSecondOfDay() *  1000;
    }

    public boolean isChecked() {
        return checked;
    }
}

Then the deserialization works out of the box:

ObjectMapper mapper = new ObjectMapper();

// Changed the spelling from "cheked" to "checked"
String json = "{\"timeLeft\": \"10:00\", \"checked\": true}";
final TimeLeftPojo timeLeftPojo = mapper.readValue(json, TimeLeftPojo.class);
System.out.println(timeLeftPojo.toMillisecondOfDay());

The output will be:

36000000

The JavaDoc for @JsonCreator can be found here.

Note that the time pattern is "HH:mm", not "HH:MM" as in the original query ("M" is month, not minute).

Upvotes: 2

pDer666
pDer666

Reputation: 727

Do you have any object on server side where you map this json? Perhaps you can use an implementation of JsonSerializer/JsonDeserializer for this field and convert the time into a timestamp.

Upvotes: 0

Related Questions