jjzjj

java - 从 JAXB 转换 null java.lang.Integer 产生 0,而不是 null

coder 2024-07-04 原文

我有以下 XML:

<person>
    <id/>
    <Identifier/>
    <Surname>TEST</Surname>
    <Forename1>TEST</Forename1>
    <Forename2/>
    <Title>MR</Title>
    <Gender>M</Gender>
</person>

通过序列化以下类产生:

package anonymised.packagename;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)

@XmlType(name = "", propOrder = {
    "Id",
    "Identifier",
    "Surname",
    "Forename1",
    "Forename2",
    "Title",
    "Sex"
})

@XmlRootElement(name = "person")
public class person{

    @XmlElement(name = "id", nillable=true)
    protected Integer Id;
    public Integer getId(){
        return Id;
    }

    public void setId(Integer value){
        this.Id = value;
    }

    @XmlElement(name = "Identifier", nillable=true)
    protected String Identifier;
    public String getIdentifier(){
        return Identifier;
    }

    public void setIdentifier(String value){
        this.Identifier = value;
    }

    @XmlElement(name = "Surname", nillable=true)
    protected String Surname;
    public String getSurname(){
        return Surname;
    }

    public void setSurname(String value){
        this.Surname = value;
    }

    @XmlElement(name = "Forename1", nillable=true)
    protected String Forename1;
    public String getForename1(){
        return Forename1;
    }

    public void setForename1(String value){
        this.Forename1 = value;
    }

    @XmlElement(name = "Forename2", nillable=true)
    protected String Forename2;
    public String getForename2(){
        return Forename2;
    }

    public void setForename2(String value){
        this.Forename2 = value;
    }

    @XmlElement(name = "Title", nillable=true)
    protected String Title;
    public String getTitle(){
        return Title;
    }

    public void setTitle(String value){
        this.Title = value;
    }

    @XmlElement(name = "Gender", nillable=true)
    protected String Gender;
    public String getGender(){
        return Gender;
    }

    public void setGender(String value){
        this.Gender = value;
    }
}

我使用对象上的“set”方法和 JAXB 序列化来生成上面的 XML,选择 java.lang.Integer 对象正是因为它们可以为 null。

然后我使用以下代码将 XML(由 xmlString 表示)反序列化回对象:

DocumentBuilder builder = fac.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
String className = "anonymised.packagename." + doc.getDocumentElement().getNodeName();
Class<?> c = Class.forName(className);
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller um = context.createUnmarshaller();
Object o = c.cast(um.unmarshal(new StringReader(xmlString)));

JAXBContext jbc = JAXBContext.newInstance(c);
Marshaller jm = jbc.createMarshaller();

jm.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jm.marshal(o, new File("C:\\person.xml"));

生成以下 XML 文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <id>0</id>
    <Identifier/>
    <Surname>TEST</Surname>
    <Forename1>TEST</Forename1>
    <Forename2></Forename2>
    <Title>MR</Title>
    <Gender>M</Gender>
</person>

原为 null 的 java.lang.Integer 现在为 0。这怎么可能?从断点来看,从 null 到 0 的变化发生在转换过程中,但我不明白为什么会这样。在类型转换过程中是否有某种转换为简单的 int ?有没有办法避免这种现象?我认为在 XML 元素声明中添加“nillable”会有所帮助,但事实并非如此。

最佳答案

JAXB 不会将任何空元素视为 null 的有效表示。如果您反省 String 类型的 indentifier 属性,您会在解码空元素后看到它是 ""

null 的两个有效表示是:

  1. 缺少元素,对应于 XML 架构中的 minOccurs="0"。这是默认行为。
  2. xsi:nil="true" 在元素上。这对应于 XML 架构中的 nillable="true"。如果您使用 @XmlElement(nillable=true) 注释您的属性,您将获得此行为。

更新

Thanks for your answer. On point 2, I have annotated my property with @XmlElement(nillable = true) in the class above, but I haven't got the behaviour you describe in my XML. Does your answer mean that, in the production of any XML that should be null, the attribute xsi:nil needs to explicitly be set to true?

当您使用 @XmlElement(nillable=true) 时,期望对应的 XML 元素的 xsi:nil 属性设置为 true 喜欢以下内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <id xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</person>

I'm happy with the idea that the Identifier element is an empty String, not null, but the id element, because it's an Integer should be null, not 0, right?

您绝对可以提出这样的论点。使用 JAXB RI,如果您将 Integer 属性更改为 Long,您将看到您正在寻找的行为。

关于java - 从 JAXB 转换 null java.lang.Integer 产生 0,而不是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27115364/

有关java - 从 JAXB 转换 null java.lang.Integer 产生 0,而不是 null的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  4. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  7. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  8. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐