我正在尝试将 LinkedHashMap 序列化为特定对象。但是我在该对象中的属性有不同的名称,我如何以正确的方式匹配这些属性? 我尝试使用 @JsonValue 和 @JsonProperty 注释,但类上的属性值始终为 null。
我有这张 map :
Map<String, String> myMap = new LinkedHashMap<>();
myMap.put("user_name", "John Doe");
我想序列化到这个对象:
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class DummyUser {
private String userName;
}
我正在尝试使用这种方法:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.convertValue(myMap, DummyUser.class);
最佳答案
您需要将映射配置应用于 POJO,特别是在 userName 的 setter 方法中:
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class DummyUser {
private String userName;
@JsonProperty("user_name")
public setUserName(String un) {...}
}
ObjectMapper mapper = new ObjectMapper();
Map<String, String> myMap = new LinkedHashMap<>();
myMap.put("user_name", "John Doe");
mapper.readValue(myMap, DummyUser.class);
关于java - 使用对象属性中的别名将映射序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47982956/