【发布时间】:2016-04-04 11:14:45
【问题描述】:
我一直在尝试淡化包含 Date 的 JSON 字符串,但出现以下异常-
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.util.Date from String value '/Date(1458672480000)/': not a valid representation (error: Unparseable date: "/Date(1458672480000)/" (at offset 0))
at [Source: java.io.StringReader@32e26583; line: 1, column: 199]
代码详情如下-
数据模型-
@JsonIgnoreProperties(ignoreUnknown = true)
public class DataModel {
public Integer Capacity;
public Long Id;
public String Name;
public Date StartDate;
public Date EndDate;
public String Message;
public Integer LocationId;
public Boolean IsValid;
public Integer[] NickNames = new Integer[0];
}
JSON 字符串-
{"d":[{"__type":"my.package.name.className","Id":1,"Name":"xxx","PlaceId":2,"Message":"","IsValid":false,"NickNames":[],"StartDate":"\/Date(1458672480000)\/","EndDate":"\/Date(1458689400000)\/","Size":0,"StringStartDate":"2016-03-22T14:48:00-04:00","StringEndDate":"2016-03-22T19:30:00-04:00"}]}
反序列化代码-
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
mapper.setDateFormat(dateFormat);
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
TypeReference<HashMap<String,DataModel[]>> typeRef= new TypeReference<HashMap<String,DataModel[]>>(){};
HashMap<String,DataModel[]> newSessions = mapper.readValue(data, typeRef);
JSON 字符串有问题吗?如果不是,反序列化的正确方法是什么?
【问题讨论】:
-
1458672480000 而不是 Date(1458672480000)?
-
您的 json 中有一个名为
StringStartDate的字段,其中包含您所期望的数据。但是,该字段不会出现在您的 DataModel 中。 json 中的StartDate字段包含无效内容,因此无法反序列化为java.util.Date。