【发布时间】:2016-11-09 20:37:00
【问题描述】:
我有一个 JSON,其中一个值是 ISO-8601 日期时间字符串。 我需要将其转换为 java.util.Date。我该怎么做?
我不确定下面的代码是否正确。
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
import java.util.Map;
public class CustomObjectMapper extends ObjectMapper {
private static final long serialVersionUID = 2686298573056737140L;
private static final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" );
public CustomObjectMapper() {
super.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
super.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
super.setSerializationInclusion(JsonInclude.Include.NON_NULL);
super.setDateFormat(df);
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new CustomObjectMapper();
Map<String, Object> map = mapper.readValue(JSON, new TypeReference<Map<String, Object>>(){});
System.out.println(map);
for(String key: map.keySet()) {
Object val = map.get(key);
System.out.println("keyName is " + key + " value is " + val + " value type is " + val.getClass());
}
}
private static final String JSON = "{\"mybool\":true,\"mydate\":\"2016-02-11T18:30:00.511-08:00\",\"mystring\":\"test\",\"myint\":1234}";
}
当我打印地图内容时,我看到“mydate”值显示为字符串。
key is mybool value is true value type is class java.lang.Boolean
key is mydate value is 2016-02-11T18:30:00.511-08:00 value type is class java.lang.String
key is mystring value is test value type is class java.lang.String
key is myint value is 1234 value type is class java.lang.Integer
我可以将 Jackson 配置为键“mydate”的值类型必须为 java.util.Date 的位置吗?
【问题讨论】:
-
如果您正在阅读地图,我认为您无法指定哪个值是日期。