简体   繁体   English

使用 ZAB6632D55A4B3743FA21DAF85F26 将具有单个变量的 Java Object 转换为 XML

[英]Convert Java Object with single variable to XML using JAXB

Let's say I have class Foo假设我有 class Foo

@XmlRootElement(name="foo")
public class Foo {
    @XmlElement(name = "id")
    private Bar variable;
    @XmlElement
    private String name;
}

and class Bar和 class 酒吧

public class Bar {
    @XmlElement
    private String id;
}

and I want to get an XML file like我想得到一个 XML 文件,比如

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<foo>
    <id>bar</id>
    <name>foo</name>
</foo>

but instead I get when I run the marshal但是当我运行元帅时,我得到了

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<foo>
    <id>    
        <id>bar</id>
    </id>
    <name>foo</name>
</foo>

I can't use getters or setters due to having to follow strict encapsulation rules and I can't simply delete the Bar class because the Bar clase holds important business logic in it's constructor.由于必须遵循严格的封装规则,我不能使用 getter 或 setter,而且我不能简单地删除 Bar class 因为 Bar 类在其构造函数中包含重要的业务逻辑。

I know I can use a private getter to do that but it seems like a weird hack and I was wondering if there is a cleaner solution using tags.我知道我可以使用私有 getter 来做到这一点,但这似乎是一个奇怪的 hack,我想知道是否有使用标签的更清洁的解决方案。

I have tried to look into how Jaxb converts String objects to a simple XML string element without success, but I think it was probably hardcoded.我试图研究 Jaxb 如何将字符串对象转换为简单的 XML 字符串元素但没有成功,但我认为它可能是硬编码的。

Thanks to the previous answer here I managed to find a way to do this.多亏了以前的答案,我设法找到了一种方法来做到这一点。

Class foo doesn't change, it stays as intended Class foo 没有改变,它保持原样

Class bar however, stops using @XmlElement and starts using @XmlValue , so it would look like this: Class bar 然而,停止使用@XmlElement并开始使用@XmlValue ,所以它看起来像这样:

public class Bar {
    @XmlValue
    private String id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM