杰克逊改变时间戳格式

时间:2018-04-26 10:58:46

标签: java json spring spring-mvc jackson

我通过json webservice输出一些数据库结果。简单如下:

@GetMapping(produces = "application/json")
public List<Map<String, Object>> get(Param params) {
    return jdbcTemplate.queryForList(sql, params)
}

问题:java.sql.Timestamp转换为格式2018-04-26T07:52:02.000+0000,而普通数据库输出则为2018-04-26 07:52:02.0

问题:是否有任何配置属性告诉spring只是通过从数据库接收的本机时间戳,而不是用jackson逻辑转换它?

我想全局更改java.sql.Timestamp格式

重要:请不要建议任何注释!我没有任何bean / pojo,我只是将普通数据库结果作为Map返回。

2 个答案:

答案 0 :(得分:2)

  

我想全局更改ObjectMapper格式

将日期格式设置为ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S")); 实例:

ObjectMapper

在Spring应用程序中,您可以将@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S")); return mapper; } 实例公开为bean:

spring.jackson.date-format

在Spring Boot中,您可以使用属性spring.jackson.date-format: yyyy-MM-dd HH:mm:ss.S 来定义日期格式:

Map<String, Object> data = new HashMap<>();
data.put("date", new Timestamp(ZonedDateTime.now().toInstant().toEpochMilli()));
System.out.println(mapper.writeValueAsString(data));

有关常见应用程序属性的更多详细信息,请参阅documentation

请考虑以下代码:

{"date":"2018-04-26 07:25:14.408"}

它将打印:

Private Sub Worksheet_Change(ByVal Target As Range)


Dim Oldvalue As String
Dim Newvalue As String

On Error GoTo Exitsub
If Target.Address = "$S10" Then
    If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
    GoTo Exitsub
    Else: If Target.Value = "" Then GoTo Exitsub Else
        Application.EnableEvents = False
        Newvalue = Target.Value
        Application.Undo
        Oldvalue = Target.Value
        If Oldvalue = "" Then
            Target.Value = Newvalue
        Else
            Target.Value = Oldvalue & ", " & Newvalue
        End If
    End If
End If
Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True
End Sub

答案 1 :(得分:0)

或者如果你需要这个作为Spring @Bean

    @Bean
    public JacksonProperties jacksonProperties() {
        JacksonProperties properties = new JacksonProperties();
        properties.setDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // put any pattern you need
        return properties;
    }
相关问题