MessageBodyReader/Writer for Generic class

最后都变了- 提交于 2019-12-11 06:53:26

问题


I have a class

public class Tree<T> {
    private T value;
    private Tree<T> parent;
    private List<Tree<T>> children;
    ...
}

I then want to make a MessageBodyReader and Writer to be able to produce and consume JSON that represent instances of this class, but without circular references. So a JSON document would exclude the parent.

I then get a method I shall implement that looks like this

@Override
public Tree<?> readFrom(Class<Tree<?>> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

How can I determine what ? is in Class<Tree<?>> or in genericType? Or said in other words: How can I determine what kind of object the Tree class is carrying?


回答1:


The information you're looking for will be stored in genericType parameter. The actual type of genericType depends on the complexity of the Tree<T> hierarchy you're trying to (un)marshall JSON into. Note that the genericType is derived (for reader) from resource method signature. For example for a method like:

@GET
public String get(final Tree<String> tree) { ... }

the genericType would contain expected generic type information. But for a method like:

@GET
public String get(final Tree tree) { ... }

the parameter type of the Tree would be Object.

Note: Instead of (un)marshalling Java Objects into JSON yourself you can use JSON modules that are available in Jersey and try the JAXB approach of JSON<->Object (here you can use the @XmlTransient annotation to omit parent from (un)marshalling). In Jersey 2.3+ there is also a concept of entity-filtering which lets you choose which fields should be considered to be (un)marshalled into/from JSON.



来源:https://stackoverflow.com/questions/19779512/messagebodyreader-writer-for-generic-class

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