【问题标题】:ObjectMapper could not convert map to POJO in Java 11ObjectMapper 无法在 Java 11 中将映射转换为 POJO
【发布时间】:2021-08-29 13:09:23
【问题描述】:

现在我正在使用 ObjectMapper 将 Map 转换为 Java 中的 POJO,这是我的代码:

@Override
    public RssSubSourceExtDTO getChannelAnalysisInfo() {
        Map<String, Object> analysisInfo = customRssSubSourceMapper.getSourceInfo(new SubSourceRequest());
        final ObjectMapper mapper = new ObjectMapper();
        final RssSubSourceExtDTO pojo = mapper.convertValue(analysisInfo, RssSubSourceExtDTO.class);
        return pojo;
    }

但是结果POJO的所有属性都是空的。我试图调整 POJO 属性名称,并将 POJO 属性调整为 Object 类型,但仍然无法将值从 map 转换为 POJO。这是我的 POJO 定义:

import java.io.Serializable;

/**
 * @author dolphin
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class RssSubSourceExtDTO implements Serializable {
    /**
     * support increment pull channel count
     * rss_sub_source.id
     *
     * @mbggenerated
     */
    private Object incrementPullChannelCount;

    /**
     * do not support increment pull channel count
     * rss_sub_source.created_time
     *
     * @mbggenerated
     */
    private Long fullPullChannelCount;

    /**
     * 
     * rss_sub_source.editor_pick
     *
     * @mbggenerated
     */
    @ApiModelProperty(value = ")")
    private Long editorPickChannelCount;
}

这是现在的调试视图:

我应该怎么做才能解决它?

【问题讨论】:

    标签: java


    【解决方案1】:

    查看analysisInfo 映射,字段名称与 POJO 中的实例变量名称不匹配。例如,字段名称为fullPullChannelCount,而您的地图名称为fullpullchannelcount

    使用@JsonProperty将map中的属性名映射到POJO中的变量。

    @JsonProperty("fullpullchannelcount")
    private Long fullPullChannelCount;
    
    @JsonProperty("editor_pick_channel_count")
    private Long editorPickChannelCount;
    ....
    

    见:When is the @JsonProperty property used and what is it used for?

    或者,您可以更改序列化数据中的属性名称与实例变量名称匹配。

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 1970-01-01
      • 2018-12-29
      • 2021-12-11
      • 1970-01-01
      • 2019-06-25
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多