简体   繁体   中英

how to convert list fields to map in java

I'm getting an error trying to change a Java object to a map. It is assumed that there is a list among the fields. Is there any solution???

    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
   }

error message: Cannot deserialize value of type java.lang.String from Array value (token JsonToken.START_ARRAY )

Your fields have visibility private, by default the object mapper will only access properties that are public or have public getters/setters. You can either create getter and setters if it fits your use-case or change the objectMapper config

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

More about it - http://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/ObjectMapper.html#setVisibility(com.fasterxml.jackson.annotation.PropertyAccessor,%20com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility) and https://www.baeldung.com/jackson-jsonmappingexception

and then use Use Map<String, Object> as the TypeReference

// 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);

Let me know if you face any other issue.

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