Reputation: 45
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
)
Upvotes: 1
Views: 1875
Reputation: 3358
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.
Upvotes: 2