[英]how to convert list fields to map in java
I'm getting an error trying to change a Java object to a map.我在尝试将 Java 对象更改为地图时遇到错误。 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
)错误消息:无法从数组值(令牌JsonToken.START_ARRAY
)中反序列化java.lang.String
类型的值
Your fields have visibility private, by default the object mapper will only access properties that are public or have public getters/setters.您的字段具有私有可见性,默认情况下,对象映射器将仅访问公共属性或具有公共 getters/setters 的属性。 You can either create getter and setters if it fits your use-case or change the objectMapper config如果适合您的用例,您可以创建 getter 和 setter,或者更改 objectMapper 配置
// 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关于它的更多信息 - 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)和https://www.baeldung.com/jackson-jsonmappingexception
and then use Use Map<String, Object> as the TypeReference然后使用 Use Map<String, Object> 作为 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.如果您遇到任何其他问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.