【问题标题】:Spring JSON converter. How to bind different types弹簧 JSON 转换器。如何绑定不同的类型
【发布时间】:2015-02-10 08:04:14
【问题描述】:

我有一个带有数据的 ajax 调用:"{"timeLeft": 12:33, "cheked": true}"。在客户端 timeleft 格式:HH:MM,但在服务器端我们需要将其转换为毫秒(Long)。如何使用 MappingJackson2HttpMessageConverter 做到这一点? 在 Spring 提交表单后,我们可以使用 PropertyEditors。杰克逊转换器中的 json 数据有类似的东西吗?谢谢

【问题讨论】:

    标签: java json spring spring-mvc jackson


    【解决方案1】:

    MappingJackson2HttpMessageConverter 使用 Jackson 的 ObjectMapper 将 JSON 反序列化为 Pojos(或从 JSON 反序列化为 Maps/JsonNodes)。因此,一种方法是创建一个作为反序列化对象的 POJO。

    如果预期时间值确实是“HH:MM”,其中“HH”实际上表示“一天中的小时 (0-23)”,而“MM”表示“小时中的分钟 (0-59)”,那么以下方法可以用。

    将自定义 @JsonCreator 添加到您的支持 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;
        }
    }
    

    然后反序列化开箱即用:

    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());
    

    输出将是:

    36000000

    @JsonCreator 的 JavaDoc 可以是 be found here。

    请注意,时间模式是“HH:mm”,而不是原始查询中的“HH:MM”(“M”是月,而不是分钟)。

    【讨论】:

      【解决方案2】:

      您在映射此 json 的服务器端是否有任何对象?也许您可以为此字段使用 JsonSerializer/JsonDeserializer 的实现,并将时间转换为时间戳。

      【讨论】:

        猜你喜欢
        • 2013-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 2020-02-25
        • 1970-01-01
        相关资源
        最近更新 更多