我有一个 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}";
}
当我打印 map 内容时,我看到“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 吗?
最佳答案
假设您知道 JSON 结构,那么您可以使用 POJO 来映射其属性并使用 @JsonFormat注释(可从 Jackson 2.0 获得)如下:
import com.fasterxml.jackson.annotation.JsonFormat
class MyPojo {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
Date mydate
String mystring
Boolean mybool
Integer myint
}
然后在您的映射器类上:
MyPojo myPojo = mapper.readValue(JSON, MyPojo.class);
关于java - Jackson 读取 JSON 并转换为 Map<String,Object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40515593/