简体   繁体   中英

"com.fasterxml.jackson.databind.JsonMappingException: Expected type float, integer, or string." converting the java.time.Instant with ObjectMapper

I am mapping the linkedHashMap to my Custom Pojo class using the below code.

ObjectMapper mapper = new ObjectMapper();**mapper.registerModule(new ParameterNamesModule()).registerModule(new Jdk8Module()).registerModule(new JavaTimeModule());** mapper.findAndRegisterModules(); mapper.convertValue(wrapper.getObject(), wrapper.getClassType());

This is giving me the below exception "com.fasterxml.jackson.databind.JsonMappingException: Expected type float, integer, or string."

Previously, It was giving me a different exception(com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.Instant: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)) and after adding the highlighted code to the mapper then it started giving this exception. Could anyone help me figure out how to solve this exception?

I have the following test which works for me on Jackson 2.8.9.

public class FooTest {

    public static class CustomBean implements Serializable {
        private static final long serialVersionUID = 1L;
        @JsonInclude(JsonInclude.Include.NON_DEFAULT)
        public Instant time;
        public String recordName;

        public CustomBean() {
        }

        @Override
        public String toString() {
            return String.format("name:%s time:%s", recordName, time);
        }
    }

    @Test
    public void test_me() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.findAndRegisterModules();

        Map<String, Object> data = new LinkedHashMap<>();
        data.put("recordName", "test");
        data.put("time", Instant.now());

        String json = mapper.writeValueAsString(data);
        System.out.println(json);

        CustomBean bean = mapper.convertValue(data, CustomBean.class);
        System.out.println(bean);
    }

}

The output I get is:

{"recordName":"test","time":1536738977.085000000}
name:test time:2018-09-12T07:56:17.085Z

Comparing this to your JSON output in the comment, it feels like your Instant is not being serialised correctly. Even though you are loading the JavaTimeModule so I don't really know why that is happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM