且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-06 17:49:45

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

First, your list annotation is missing the the entries name:

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

否则使用< string> ...</string> ,而不使用< object> ...</object> .
您可以通过在列表的注释中添加 type = String.class 来防止空指针异常.但是,这不能解决主要问题.

Otherwise <string>...</string> is used, not <object>...</object>.
You can prevent that nullpointer excpetion by adding type = String.class to your list's annotation. However, this doesn't fix the main problem.

通常,空标记/ null -元素不会添加到结果中.

In general empty tags / null-elements will not be added to the result.

以下是使用 Converter 来解决此问题的示例.

Here's an example how to solve this problem with a 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 )
            {
                /* 
                 * If the value is null it's added too. You also can add some
                 * kind of null-replacement element here too.
                 */
                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);
            }
        }

    }

}

根据评论中的内容,您需要做一些进一步的工作.

As written in the comments, you have to do some further work.

结果:

testNullsInParams()

testNullsInParams()

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

testDeserializeNull()

testDeserializeNull()

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