gpt4 book ai didi

java - JAXB 编码 : treat empty object like it's null

转载 作者:行者123 更新时间:2023-12-02 12:58:51 24 4
gpt4 key购买 nike

我想用一个简单的例子来解释我的问题:

Foo:

@SomeXMLAnnotations
public class Foo {
// Bar is just a random class with its own XML annotations
@XmlElement(required = true)
Bar someBarObj;

boolean chosen = true;
boolean required = true;

public Foo(){
chosen = false;
}

public Foo(Bar someBarObj){
this.someBarObj = someBarObj;
}
}

我的类(class):

@SomeXMLAnnotations
public class MyClass {

@XmlElement(required = false)
Foo anyFooObj;

@XmlElement(required = true)
Foo anyFooObjRequired;

public MyClass (){ }

public MyClass (Foo anyFooObj, Foo anyFooObjRequired){
this.anyFooObj = anyFooObj;
if(anyFooObj == null)
this.anyFooObj = new Foo();
/*
* This is the reason why i can't let 'anyFooObj' be 'null'.
* So 'anyFooObj' MUST be initialized somehow.
* It's needed for some internal logic, not JAXB.
*/
anyFooObj.required = false;

this.anyFooObjRequired = anyFooObjRequired;
}
}

示例对象:

Foo fooRequired = new Foo(new Bar());
MyClass myObj = new MyClass(null, fooRequired);

当我现在尝试编码(marshal) myObj 时,它会抛出如下异常:

org.eclipse.persistence.oxm.record.ValidatingMarshalRecord$MarshalSAXParseException; 
cvc-complex-type.2.4.b: The content of element 'n0:anyFooObj ' is not complete.
One of '{"AnyNamespace":someBarObj}' is expected.

发生这种情况是因为 anyFooObj 已初始化,但它是必需的,成员someBarObj 不是。

可能的解决方案:

我知道我可以将此方法添加到MyClass:

void beforeMarshal(Marshaller m){
if(! anyFooObj.chosen)
anyFooObj= null;
}
}

但是我有很多类,并且这些类有很多非必填字段。因此,这个解决方案需要很长时间,而且看起来也不是一个合适的解决方案。

我的问题:

有没有办法告诉 JAXB 它应该像对待 null 一样对待空对象?或者当元素设置不正确时它应该忽略它。例如这样的事情:

@XmlElement(required = false, ingnoreWhenNotMarshallable = true)
Foo anyFooObj;

注意:

我不是代码的开发人员。我只需将 JAXB 添加到项目中,并使所有内容都与给定的 XSD 文件兼容。我不允许更改类之间的关系。

最佳答案

我认为你试图让 JAXB 编码器做一些它实际上不是设计要做的事情,所以我想说你在这里进入了黑客领域。我建议推迟要求,以便从一开始就避免出现此问题。

也就是说,如果您必须这样做,那么考虑到您要求避免为每个类/字段编写代码,我认为您会希望为此使用反射 - 我在下面提供了一个示例,该示例可以反射性地检查值所有领域。

有用的扩展是:

  • 让它也考虑 getter 方法
  • 通过要求字段具有附加注释来选择启用 null 设置行为 - 您可以将其命名为 @JAXBNullIfEmpty

示例.java:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.StringWriter;
import java.lang.reflect.Field;

public class Example
{
public abstract static class JAXBAutoNullifierForEmptyOptionalFields
{
void beforeMarshal(Marshaller x)
{
try
{
for (Field field : this.getClass().getFields())
{
final XmlElement el = field.getAnnotation(XmlElement.class);

// If this is an optional field, it has a value & it has no fields populated then we should replace it with null
if (!el.required())
{
if (JAXBAutoNullifierForEmptyOptionalFields.class.isAssignableFrom(field.getType()))
{
final JAXBAutoNullifierForEmptyOptionalFields val = (JAXBAutoNullifierForEmptyOptionalFields) field.get(
this);

if (val != null && !val.hasAnyElementFieldsPopulated())
field.set(this, null); // No fields populated, replace with null
}
}
}
}
catch (IllegalAccessException e)
{
throw new RuntimeException("Error determining if class has all required fields: " + this, e);
}
}


boolean hasAnyElementFieldsPopulated()
{
for (Field field : this.getClass().getFields())
{
try
{
if (field.isAnnotationPresent(XmlElement.class))
{
// Retrieve value
final Object val = field.get(this);

// If the value is non-null then at least one field has been populated
if (val != null)
{
return true;
}
}
}
catch (IllegalAccessException e)
{
throw new RuntimeException("Error determining if class has any populated JAXB fields: " + this, e);
}
}

// There were no fields with a non-null value
return false;
}
}

@XmlRootElement
public static class MyJAXBType extends JAXBAutoNullifierForEmptyOptionalFields
{
@XmlElement
public String someField;

@XmlElement
public MyJAXBType someOtherField;


public MyJAXBType()
{
}


public MyJAXBType(final String someField, MyJAXBType someOtherField)
{
this.someField = someField;
this.someOtherField = someOtherField;
}
}


public static void main(String[] args) throws Exception
{
final Marshaller marshaller = JAXBContext.newInstance(MyJAXBType.class).createMarshaller();

MyJAXBType innerValue = new MyJAXBType(); // Unpopulated inner value
MyJAXBType value = new MyJAXBType("some text value", innerValue);

final StringWriter sw = new StringWriter();

marshaller.marshal(value, sw); // Omits "someOtherField"

System.out.println(sw.toString());
}
}

关于java - JAXB 编码 : treat empty object like it's null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44354356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com