英文:
Convert an empty tag in XML to java attribute using jackson-dataformat-xml library
问题
Element2
的属性在Element1
中始终被设置为false
。是否有办法在Element2标签存在时将其设置为true
,否则设置为false
?
Element2
的属性在Element1
中始终被设置为false
。是否有办法在Element2标签存在时将其设置为true
,否则设置为false
?
英文:
I have below XML
which need to be converted to POJO
in Spring Boot
app. I am using jackson-dataformat-xml
module for this.
<Root>
<Element1 ns="xxx">
<Element2/>
</Element1>
</Root>
Root Pojo:
@JacksonXmlRootElement(localName = "Root")
public class Root {
@JacksonXmlProperty(localName = "Element1")
private Element1 element1;
public String getElement1() {
return element1;
}
public void setElement1(String element1) {
this.element1 = element1;
}
}
Element1 Pojo:
public class Element1 {
@JacksonXmlProperty(isAttribute = true)
private String ns;
@JacksonXmlProperty(localName = "Element2")
private boolean element2;
public boolean getElement2() {
return element2;
}
public void setElement2(boolean element2) {
this.element2 = element2;
}
}
Property element2
in Element1
is always set to false
. Is there any way to set it to true
if Element2 tag is present; otherwise false
?
答案1
得分: 1
默认情况下,Jackson
使用 com.fasterxml.jackson.databind.deser.BeanDeserializer
类来反序列化给定的 XML
元素到 POJO
。只有在 XML
负载中存在相应节点时,此反序列化程序才会调用 setter
方法。如果节点不存在于负载中,则不会调用 setter
方法。我们可以利用这种行为。
因为我们希望始终设置为 true
,所以我们应该创建一个新的私有 setter
方法,并使用 @JacksonXmlProperty
注解强制 Jackson
使用它。下面是一个示例:
class Element1 {
@JacksonXmlProperty(isAttribute = true)
private String ns;
private boolean element2;
public boolean getElement2() {
return element2;
}
public void setElement2(boolean element2) {
this.element2 = element2;
}
@JacksonXmlProperty(localName = "Element2")
private void setElement2ByJackson(boolean ignored) {
this.element2 = true;
}
}
英文:
By default Jackson
uses com.fasterxml.jackson.databind.deser.BeanDeserializer
class do deserialise given XML
element to POJO
. This deserialiser invokes setter
method only if corresponding node exists in XML
payload. In case, node doesn't exist in payload - setter
method is not invoked. We can utilize this behaviour.
Because we want to set always true
we should create new private setter method and force Jackson
to use it with @JacksonXmlProperty
annotation. Below you can see example:
class Element1 {
@JacksonXmlProperty(isAttribute = true)
private String ns;
private boolean element2;
public boolean getElement2() {
return element2;
}
public void setElement2(boolean element2) {
this.element2 = element2;
}
@JacksonXmlProperty(localName = "Element2")
private void setElement2ByJackson(boolean ignored) {
this.element2 = true;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论