Android解析java.sql.Timestamp抛出格式异常问题求助
问题描述
后端API的timestamp字段定义如下:
@JsonProperty(access = JsonProperty.Access.READ_ONLY) @Column(name = "timestamp") @CreationTimestamp private Timestamp timestamp;
API返回的JSON响应格式为:
{"timestamp":"2023-01-05T12:33:32.883+00:00"}
Android端采用以下代码解析:
x.setTimestamp(java.sql.Timestamp.valueOf(arr.getJSONObject(i).getString("timestamp")));
运行时抛出异常:
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
可行解决方案
方案1:后端调整时间序列化格式
在实体类的timestamp字段上添加@JsonFormat注解,指定符合java.sql.Timestamp解析要求的格式:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Column(name = "timestamp") @CreationTimestamp private Timestamp timestamp;
修改后API返回的时间会变为2023-01-05 12:33:32.883,可直接用Timestamp.valueOf()解析。
方案2:Android端自定义解析逻辑(不修改后端)
如果无法调整后端,可在Android端对返回的ISO格式时间做转换:
方式A:字符串格式化后解析
String rawTime = arr.getJSONObject(i).getString("timestamp"); // 替换T为空格,截断时区部分 String formattedTime = rawTime.replace("T", " ").split("\\+")[0]; x.setTimestamp(java.sql.Timestamp.valueOf(formattedTime));
方式B:用Java 8+的Instant类解析
String rawTime = arr.getJSONObject(i).getString("timestamp"); Instant instant = Instant.parse(rawTime); x.setTimestamp(java.sql.Timestamp.from(instant));
方式C:兼容旧版本的SimpleDateFormat解析
String rawTime = arr.getJSONObject(i).getString("timestamp"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); Date date = sdf.parse(rawTime); x.setTimestamp(new java.sql.Timestamp(date.getTime()));
方案3:使用序列化库自动解析(推荐)
放弃手动JSONObject解析,用Gson或Jackson等序列化库直接将JSON转换为实体类,这些库会自动处理ISO时间到Timestamp的映射:
Gson示例
// 定义对应实体类 public class YourEntity { private java.sql.Timestamp timestamp; // 其他字段及getter/setter } // 解析JSON YourEntity entity = new Gson().fromJson(jsonString, YourEntity.class);
Jackson示例
ObjectMapper mapper = new ObjectMapper(); YourEntity entity = mapper.readValue(jsonString, YourEntity.class);
内容的提问来源于stack exchange,提问作者TSSK
相关产品推荐
相关产品推荐

