【问题标题】:how to get rid of outer-class reference in xstream output?如何摆脱 xstream 输出中的外部类引用?
【发布时间】:2014-05-15 09:22:52
【问题描述】:

我使用 xstream 将具有嵌套类的对象编组为 xml 字符串, 我这样写:

public static String java2xml(Object obj, Class<?> T) {

    XStream xstream = new XStream(new StaxDriver());
    xstream.processAnnotations(T);
    String xml = xstream.toXML(obj);

    return xml;
}   

但我在输出字符串中得到了&lt;outer-class reference="../.."/&gt;

对象类是:

public class Foo {
    private String foocontent;
    private Bar bar;

    // getter and setter


    public class Bar {
        private String blabla;
        // getter and setter
    }

}

我用这个代码创建了一个Foo

    Foo foo = new Foo();
    Bar bar = foo.new Bar();
    bar.setBlabla("hello");
    foo.setBar(bar);
    String fooxml = Xutil.java2xml(foo, Foo.class);
    System.out.println(fooxml);

整个xml是:

<?xml version="1.0" ?>
<me.mypackage.Foo>
    <bar>
        <blabla>hello</blabla>
        <outer-class reference="../.."/>
    </bar>
</me.mypackage.Foo>

问题1:我怎样才能摆脱outer-class 部分?

问题2:如何用xstream制作格式漂亮的xml字符串?

在上一篇文章中,我有很多情绪化的问题,使我的问题不清楚,我编辑了我的帖子并列出了我要寻求的帮助,谢谢。

【问题讨论】:

    标签: java xml xstream


    【解决方案1】:

    使用PrettyPrintWriterStringWriter 一起获得漂亮的格式,如下所示:

    public static String java2xml(Object obj, Class<?> T) {
        XStream xstream = new XStream(new StaxDriver());
        xstream.processAnnotations(T);
        StringWriter stringWriter = new StringWriter();
        xstream.marshal(obj, new PrettyPrintWriter(stringWriter));
        return stringWriter.toString();
    }
    

    至于&lt;outer-class reference="../.."/&gt; 问题,如果您没有从Bar 引用任何Foo 类成员,您可以通过将Bar 类定义为static 来摆脱&lt;outer-class&gt; 标记

    【讨论】:

    • ...您还没有将栏添加到 Foo 中
    • Bar 部分是内部类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2011-03-23
    • 2021-04-25
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多