Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson read JSON and convert to Map<String,Object>

Tags:

java

date

jackson

I have a JSON where one of the values is ISO-8601 datetime string. I need to convert it to java.util.Date. How do I do it?

I'm not sure if the following code is correct.

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}";


}

When I print the map content, I see that "mydate" value is showing up as 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

Can I configure Jackson where for the key "mydate" the value type has to java.util.Date?

like image 895
serverfaces Avatar asked Apr 15 '26 08:04

serverfaces


1 Answers

Assuming that you know the JSON structure then you can have a POJO to map its properties and use @JsonFormat annotation (available from Jackson 2.0) as follows:

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    
}

Then on your mapper class:

MyPojo myPojo = mapper.readValue(JSON, MyPojo.class);
like image 196
dic19 Avatar answered Apr 16 '26 21:04

dic19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!