我一直试图对包含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]
代码详情如下 -
的DataModel -
@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"}]}
De序列化代码 -
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字符串中是否有任何问题?如果没有,反序列化的正确方法是什么?
答案 0 :(得分:1)
新Date
对象的构造函数是Date(long millis)
。但是你将这个字符串传递给它 - "Date(1458672480000)"
。
从此String获取long值,然后创建Date
对象。假设你的startDate是"Date(1458672480000)"
然后 -
Date d = new Date(Long.parseLong(startDate.substring(5, 18)));
这里我们提取字符串的数字部分并将其转换为long
类型。
理想情况下,如果您的服务器直接向您发送long
值,那么您不必解析它会更好。如果long
日期值直接来自json,那么你的代码就会完美 - "startDate": 1458672480000
。