modelmapper null值跳过

时间:2017-12-14 17:14:36

标签: java null modelmapper

public class ScriptsTagHelper : TagHelper
    {
        private static readonly object ITEMSKEY = new Object();

        private IDictionary<object, object> _items => _httpContextAccessor?.HttpContext?.Items;

        private IHttpContextAccessor _httpContextAccessor;

        public ScriptsTagHelper(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var attribute = (TagHelperAttribute)null;
            context.AllAttributes.TryGetAttribute("render",out attribute);

            var render = false;

            if(attribute != null)
            {
                render = Convert.ToBoolean(attribute.Value.ToString());
            }

            if (render)
            {
                if (_items.ContainsKey(ITEMSKEY))
                {
                    var scripts = _items[ITEMSKEY] as List<HtmlString>;

                    var content = String.Concat(scripts);

                    output.Content.SetHtmlContent(content);
                }
            }
            else
            {
                List<HtmlString> list = null;

                if (!_items.ContainsKey(ITEMSKEY))
                {
                    list = new List<HtmlString>();
                    _items[ITEMSKEY] = list;
                }

                list = _items[ITEMSKEY] as List<HtmlString>;

                var content = await output.GetChildContentAsync();

                list.Add(new HtmlString(content.GetContent()));
            }
        }
    }

在我的例子中,String b可能带有空值。我的modelmapper配置如下所示:

Class A {
    private String a;
    private String b;
    private B innerObject;
}
Class B {
    private String c;
}

当我映射对象时,我得到b = null值的目标对象。

试图远离此处显示的策略:SO- Question

我错过了什么?

3 个答案:

答案 0 :(得分:2)

您是否尝试过此配置:

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());

答案 1 :(得分:1)

看起来,好像不可能。

public <D> D map(Object source, Class<D> destinationType) {
    Assert.notNull(source, "source");
    Assert.notNull(destinationType, "destinationType");
    return this.mapInternal(source, (Object)null, destinationType (String)null);
}

我用下一个包装函数解决了它。

private static <D> D map(Object source, Type destination) {
    return source == null ? null : mapper.map(source, destination);
}

也检查此问题Modelmapper: How to apply custom mapping when source object is null?

答案 2 :(得分:0)

我宁愿这样:

LocalDateTime