栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

简单框架。空值可以保留在集合中吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

简单框架。空值可以保留在集合中吗?

首先,您的列表注释缺少条目名称:

@ElementList(inline = true, required = false, entry = "object")private List<Object> params;

否则

<string>...</string>
,不使用
<object>...</object>

您可以通过添加
type = String.class
到列表的注释中来防止空指针异常。但是,这不能解决主要问题。

通常,空标记/-

null
元素不会添加到结果中。


这是一个使用来解决此问题的示例

Converter

public class SimpleframeworkTest{    // ...    @Root(name = "container", strict = false)    @Convert(NullawareContainerConverter.class)    public static class Container    {        static final Serializer ser = new Persister(new AnnotationStrategy());        // ...        public String toXml() throws Exception        { StringWriter sw = new StringWriter(); ser.write(this, sw); return sw.toString();        }        public static Container toObject(String xml) throws Exception        { return ser.read(Container.class, xml);        }        // ...    }    static class NullawareContainerConverter implements Converter<Container>    {        final Serializer ser = new Persister();        @Override        public Container read(InputNode node) throws Exception        { final Container c = new Container(); c.id = Integer.valueOf(node.getAttribute("id").getValue()); c.params = new ArrayList<>(); InputNode n; while( ( n = node.getNext("object")) != null ) {          c.params.add(n.getValue()); } return c;        }        @Override        public void write(OutputNode node, Container value) throws Exception        { ser.write(value.id, node); for( Object obj : value.params ) {     if( obj == null )     {         obj = ""; // Set a valid value if null     }     // Possible you have to tweak this by hand     ser.write(obj, node); }        }    }}

如评论中所写,您必须做一些进一步的工作。

结果:

testNullsInParams()

<container>   <integer>4000</integer>   <string>foo</string>   <string></string>   <string>bar</string></container>

testDeserializeNull()

Container [id=4000, params=[foo, null, bar]]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516147.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号