Jackson读取JSON并转换为Map <string,object>

时间:2016-11-09 20:37:01

标签: java date jackson

我有一个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”值显示为String。

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吗?

2 个答案:

答案 0 :(得分:3)

假设您知道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    
}

然后在你的mapper类上:

MyPojo myPojo = mapper.readValue(JSON, MyPojo.class);

答案 1 :(得分:1)

不,你不能。 JSON格式没有Date数据类型。它只能是String。所以你必须自己解析它到java.util.Date。 例如,使用:

new java.util.Date(javax.xml.bind.DatatypeConverter.parseDateTime(val).getTimeInMillis());