如何在java中将列表字段转换为Map

fdbelqdn  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(196)

我在尝试将Java对象更改为Map时遇到错误。假设字段之间存在列表。有什么解决方案吗???

static class User {

        private String name;
        private List<Integer> ages;
    }

    @Test
    void t3() {
        final ObjectMapper objectMapper = new ObjectMapper();

        final User kim = new User("kim", Arrays.asList(1, 2));

        objectMapper.convertValue(kim, new TypeReference<Map<String, List<Object>>>() {}); // error
        // objectMapper.convertValue(kim, new TypeReference<Map<String, Object>>() {}); // not working too
   }

错误消息:无法从数组值(标记JsonToken.START_ARRAY)反序列化java.lang.String类型的值

niknxzdl

niknxzdl1#

您的字段具有私有可见性,默认情况下,对象Map器将仅访问公共属性或具有公共getter/setter的属性。您可以创建getter和setter(如果适合您的使用情形),也可以更改objectMapper配置

// Before Jackson 2.0
objectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
// After Jackson 2.0
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

更多关于它的信息- http://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/对象Map器.html#设置可见性(com. fasterxml. jackson.注解.属性访问器,%20com.fasterxml. jackson.注解. JsonAutoDetect. Visibility)和https://www.baeldung.com/jackson-jsonmappingexception
然后使用“使用Map〈String,Object〉”作为类型引用

// Create ObjectMapper instance 
ObjectMapper objectMapper = new ObjectMapper();

// Converting POJO to Map Map<String, Object> 
map = objectMapper.convertValue(kim, new TypeReference<Map<String, Object>>() {});

// Convert Map to POJO
User kim2 = objectMapper.convertValue(map, User.class);

如果你遇到任何其他问题,请告诉我。

相关问题