Customizing error handling of JAXB unmarshall process

邮差的信 提交于 2019-12-05 11:42:52

You could add the magic afterUnmarshal method to take care of empty entries:

@XmlRootElement 
class Root{
  @XmlElement(name="entry")
  public List<Entry> entries = Lists.newArrayList();

  void afterUnmarshal(final Unmarshaller unmarshaller, final Object parent) {
    Iterator<Entry> iter = entries.iterator();
    while (iter.hasNext()) {
      if (iter.next().name == null) iter.remove();
    }
  }
}

EDIT:

Not sure if this is better suited for you, but maybe it's of help. You could also use a Pacher, e.g. if not all objects you need to fix/validate your result are available in afterUnmarshal(..)

Runs by UnmarshallingContext after all the parsing is done. Primarily used to resolve forward IDREFs, but it can run any action. (javadoc)

Here's an example:

@XmlRootElement 
class Entry{
  @XmlElement(name="name",required=true)
  public String name;

  private boolean isValidEntry() {
    return name != null;
  }

  void afterUnmarshal(final Unmarshaller unmarshaller, final Object parent) {
    if (!isValidEntry()) {
      // entry not yet added to parent - use a patcher
      UnmarshallingContext.getInstance().addPatcher(new Patcher() {
        public void run() throws SAXException {
          ((Root)parent).removeEntry(this);
        }
      });
    }
  }
}

I wouldn't abuse it too much though, not only as it is Sun-only API.

But if you're really looking into something configurable that isn't part of the code of the marshalled objects itself. It might be best to look at something after unmarshalling. I wonder if Bean Validation (JSR 303) wouldn't be a perfect fit for you, e.g. using Hibernate Validator (don't get intimidated by the name, you don't need Hibernate ORM to use it). I haven't used it myself, but using a (new) standard for validation sounds reasonable, doesn't it?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!