首页 > 解决方案 > Jackson ObjectMapper 删除未在抽象或具体类中声明的属性

问题描述

我有一个抽象类说“AbstractChartConfig”。

// This is abstract class where I have some common properties of a chart and some methods
@Getter
@Setter
public abstract class AbstractChartConfig {
    
    protected String name;
    protected Map<String, Object> type;
    protected Map<String, Object> xAxis;
    protected Map<String, Object> yAxis;
    
    @JsonIgnore
    protected ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
            ;
    
    protected abstract void setChartType(Map<String, Object> chartType);
    
    public abstract void parseChart(ChartColDto column, HashMap<String, Object> chartData);
    
}

还有一个具体的类

@Getter
@Setter
public class PieChart extends AbstractChartConfig {
    //Implementing the methods here and setting the properties in abstract class
    @Override
    public HashMap<String, Object> parseChart(ChartColDto column, HashMap<String, Object> chartData) {
        HashMap<String, Object> config = column.getConfig();
        setChartType(config.getChartType());
        setXAxis(config.getXAxis());
        setYAxis(config.getYAxis());
        return mapper.convertValue(this, HashMap<String, Object>);
    }
    
    @Override
    protected void setChartType(Map<String, Object> chartType){
        if(null != chartType){
            setType(chartType);
        }
    }
    
}

并说配置就像

[
    {
        "config": {
            "name": "pie",
            "chartType": {
                "type": "pie",
                "radius": "10"
            },
            "xAxis": {
                "title": "Some Title",
                "fontSize": "16px"
            },
            "yAxis": {
                "title": "Some Title",
                "fontSize": "16px"
            },
            "zAxis": {
                "title": "Some Title",
                "fontSize": "16px"
            },
            "tooltip": {
                "format": "{point.y}"
            }
        }
    }
]

现在,问题 是当映射器将类转换为 HashMap 时,抽象类中定义的属性存在于最终结果中,但不是未声明的属性,即在本例中为 zAxis,工具提示

现在,我知道为了反序列化未声明的属性,如果我在具体类中声明它们,它可以正常工作。但这就是我不想做的。无论如何,哪个映射器将包含未声明的属性?

提前致谢。

标签: javajsonspring-bootjackson

解决方案


推荐阅读