Search code examples
javajsonjacksonpojoobjectmapper

ObjectMapper using com.jsoniter library


I have a Map<String, Object> map that was deserialized from a simple JSON string {"field1":"val1", "field2":"val2", "isReal":true}. I am trying to construct a Java object MyObject with the above fields.

I can do it using com.fasterxml.jackson.databind.ObjectMapper like so:

public static MyObject load(Map<String, Object> map) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(new ObjectMapper().writeValueAsString(map), MyObject.class);
    }

I was wondering if anyone knows how to do the same using com.jsoniter library?

I have tried to use JsonIterator.deserialize, but that doesn't take a Map as input.

I have also seen ReflectionEncoderFactory usage on the library website, but I don't fully grasp as to how I would use it to construct an object MyObject


Solution

  • As per @Scary Wombat's explanation:

    First it is necessary to convert the Map back to JSON string and then convert the JSON string to an object:

        public static MyObject load(Map<String, Object> map) throws IOException {
            return JsonIterator.deserialize(JsonStream.serialize(map), MyObject.class);
        }
    

    JsonStream.serialize(map) is the same new ObjectMapper().writeValueAsString(map)