JAXB将empty int XML属性替换为0,这对我很好,但是我需要将它存储为null.似乎我无法将DataConverterImpl类更改为自定义实现.如果有的话可以做些什么?
<xs:attribute name="Count" type="Integer0to999" use="optional">
<xs:simpleType name="Integer0to999">
<xs:annotation>
<xs:documentation xml:lang="en">Used for Integer values, from 0 to 999 inclusive</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="999"/>
</xs:restriction>
</xs:simpleType>
Run Code Online (Sandbox Code Playgroud)
在xjc架构编译之后,我得到了以下类:
@XmlAttribute(name = "Count")
protected Integer passengerCount;
Run Code Online (Sandbox Code Playgroud)
在从Sun(Oracle)parseInt()调用XML解析时 DataConverterImpl.class,代码如下,你的neve将从这段代码中获取null:
public static int _parseInt(CharSequence s) {
int len = s.length();
int sign = 1;
int r = 0;
for( int i=0; i<len; i++ ) {
char ch = s.charAt(i);
if(WhiteSpaceProcessor.isWhiteSpace(ch)) {
// skip whitespace
} else
if('0'<=ch && ch<='9') {
r = r*10 + (ch-'0');
} else
if(ch=='-') {
sign = -1;
} else
if(ch=='+') {
; // noop
} else
throw new NumberFormatException("Not a number: "+s);
}
return r*sign;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试编写一个自定义 XMLAdaptor,将整数转换为字符串(或其他对象),然后根据需要将其转换回来。在解组过程中,我想您只需要对“null”进行快速的不区分大小写的检查即可。
从这里开始: http: //download.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html
将适配器附加到 int 字段并写入正文。
您的转换器将按如下方式启动:
public class MyIntConverter extends XmlAdapter<String,Integer>
{
@Override
public String marshal(Integer value) throws Exception {
if ( value.intValue() == 0 )
return null; // Or, "null" depending on what you'd like
return value.toString();
}
@Override
public Integer unmarshal(String storedValue) throws Exception {
if ( storedValue.equalsIgnoreCase("null") )
return 0;
return Integer.valueOf(storedValue);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用它:
@XmlJavaTypeAdapter(MyIntConverter.class)
int someNumber;
Run Code Online (Sandbox Code Playgroud)
该代码未经测试,但我认为它应该可以解决问题。
| 归档时间: |
|
| 查看次数: |
4199 次 |
| 最近记录: |