ObjectMapper-如何将地图转换为POJO

时间:2018-07-21 12:41:11

标签: java jackson objectmapper

我是Java的新手,正在尝试学习objectmapper。我正在使用它将地图转换为pojo。映射中的键是字符串,所有值都是字符串值,但我要转换为映射的键值除外。 请通过下面的示例代码获得更清晰的图片。

POJO类:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import javax.annotation.Nonnull;
import java.util.Map;

public class POJOClass {
    private  String              string1;
    private Map<String, String> map1;

    @JsonCreator
    public POJOClass(@Nonnull @JsonProperty(value="String1", required = true) String string1,
                     @Nonnull @JsonProperty(value = "Map1", required = true) Map<String, String> map1) {
        this.string1 = string1;
        this.map1 = map1;
    }

    @Nonnull
    public String getString1() {
        return string1;
    }

    @Nonnull
    public Map<String, String> getMap1() {
        return map1;
    }
}

测试代码:

@Test
public void testPOJOClass() {
    Map<String, String> map = new HashMap<>();
    map.put("String1", "string");
    map.put("Map1", "{\"key1\" : \"value1\", \"key2\":\"value2\", \"key3\" : null }");

    ObjectMapper mapper = new ObjectMapper();
    POJOClass pojoClass = mapper.convertValue(map, POJOClass.class);
}

例外:

java.lang.IllegalArgumentException: Can not instantiate value of type [map type; class java.util.LinkedHashMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]] from String value ('{"key1" : "value1", "key2":"value2", "key3" : null }'); no single-String constructor/factory method
 at [Source: N/A; line: -1, column: -1]

    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3286)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3212)

尝试的变式选项:

我知道我也可以将map1字段保留为String,以后再使用对象映射器的另一个实例将其转换为map,但是我想避免使用它。有什么方法可以直接将测试代码中的字符串直接转换为上述Pojo。

我什至尝试将map1的类型从“地图”更改为“地图”,但即使这样也不起作用。

1 个答案:

答案 0 :(得分:1)

public class CustomerDeserializer extends JsonDeserializer<Map<String, String>> {

    @Override
    public Map<String, String> deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
        final ObjectMapper mapper = (ObjectMapper) p.getCodec();
    return mapper.readValue(p.getText(), new TypeReference<Map<String, String>>() {
    });
    }
}

您可以编写客户反序列化器,并在构造函数中的map1参数上注释JsonDeserialize @JsonDeserialize(using = CustomerDeserializer.class) @JsonProperty(value = "Map1", required = true) Map<String, String> map1) {