JAXB marshalling purely from interfaces

前端 未结 2 1598
甜味超标
甜味超标 2021-02-13 14:05

I have a complex hierarchy of Java interfaces that I\'d like to marshal (and not necessarily unmarshal) with JAXB. These interfaces represent objects that will be returned from

2条回答
  •  Happy的楠姐
    2021-02-13 14:43

    I think the answer is that JAXB isn't at all intended to support this and that it's foolish to try to force it. Also, JAXB-driven JSON marshaling turns out not to be ideal either.

    I ended up writing my own marshaling framework, with its own set of annotations:

    @MarshalMixin // marshal fields but not a top-level object
    interface Uuided {
      @MarshalAsString // ignore properties; just call toString()
      @MarshalId // treat as identifier for @MarshalUsingIds or cyclic ref
      UUID getId();
    }
    @MarshalMixin
    interface Named {
      @MarshalId
      String getName();
    }
    @MarshalObject // top-level marshaled object providing class name
    interface Component extends Uuided, Named {
      @MarshalAsKeyedObjectMap(key = "name") // see description below
      Map getAttributes();
    }
    @MarshalObject
    interface Attribute extends Named {
      Type getType();
      @MarshalDynamic // use run-time (not declared) type
      Object getValue();
    }
    interface ComponentAttribute extends Attribute {
      @MarshalUsingIds
      Component getDeclaringComponent();
    }
    

    The generated marshalers write to an abstraction layer (currently implemented for JSON and XML). This gives a lot more flexibility to make the output natural for different representations without a ton of annotations and adapters. E.g., what I'm calling keyed-object maps, where each object contains its map key. In JSON, you want a map, but in XML, you want a sequence:

    {..., map: {'a': {'name': 'a', ...}, 'b': {'name: 'b', ...}, ...}, ...}
    ............
    

    Seems like as many as 4 other people care about this too, so hopefully I can open-source it eventually. :-)

提交回复
热议问题