如何在jaxb中为布尔字段设置defaultValue

huangapple 未分类评论44阅读模式
英文:

How to set defaultValue for boolean field in jaxb

问题

在尝试使用@XmlJavaTypeAdapter(BooleanAdapter.class)对具有布尔属性的对象进行编组和解组时,我在JSON响应中得到了null,而不是false

我的示例对象和适配器类如下:

public class Test {

        @XmlJavaTypeAdapter(BooleanAdapter.class)
        boolean b1;

        @XmlJavaTypeAdapter(BooleanAdapter.class)
        boolean b2;

        @XmlJavaTypeAdapter(BooleanAdapter.class)
        boolean b3;

}

public class BooleanAdapter extends XmlAdapter<Boolean, Boolean> {

    @Override
    public Boolean unmarshal(Boolean v) throws Exception {
        /*
         *
         */
        return Boolean.TRUE.equals(v);
    }

    @Override
    public Boolean marshal(Boolean v) throws Exception {

        if (v) {
            return v;
        }
        return null;
    }

}

在编组时,我会移除值为false的字段,以将响应存储到数据库中。但当我获取JSON响应时,结果如下:

{
   "b1" : null,
   "b2" : true,
   "b3" : null
}

这里b1b2的值应为false,而不是null

请在这个问题上提供帮助。

英文:

While am trying to Marshaling and marshaling object with boolean properties with @XmlJavaTypeAdapter(BooleanAdapter.class) am getting 'null' instead of 'false' in json response.

my sample object and adapter classes are below.

public class Test
{

    @XmlJavaTypeAdapter(BooleanAdapter.class)
    boolean b1; 

    @XmlJavaTypeAdapter(BooleanAdapter.class)
    boolean b2; 

    @XmlJavaTypeAdapter(BooleanAdapter.class)
    boolean b3; 

}

public class BooleanAdapter extends XmlAdapter<Boolean, Boolean> {

@Override
public Boolean unmarshal(Boolean v) throws Exception {
	/*
	 * 
	 */
	return Boolean.TRUE.equals(v);
}

@Override
public Boolean marshal(Boolean v) throws Exception {

	if (v) {
		return v;
	}
	return null;
}

}

in Marshaling am removing fields with 'false' value to store the response in database.
but when i getting json response is coming like below.

{
"b1" : null,
"b2" : true,
"b3" : null
}

here b1&b2 values are false. i required value as false instead of null in response.

please help on this.

huangapple
  • 本文由 发表于 2020年4月10日 20:59:10
  • 转载请务必保留本文链接:https://java.coder-hub.com/61140768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定