问题描述
我有一个班级
public class Tree< T> {
私人T值;
私人树< T>父母;
私人列表< Tree< T>>儿童;
...
}
然后我想创建一个MessageBodyReader和Writer能够生成和使用表示此类的实例的JSON,但没有循环引用。因此,一个JSON文档将排除父项。
然后我得到一个我将执行的方法,看起来像这样
@Override
public Tree<?> readFrom(Class< Tree>> type,类型genericType,
Annotation []注释,MediaType mediaType,
多值映射< String,String> httpHeaders,InputStream entityStream)
抛出IOException, WebApplicationException {
如何确定是什么?在Class< Tree<?>>或genericType中?或者换句话说:我如何确定Tree类所携带的对象类型?
寻找将存储在 genericType 参数中。 genericType 的实际类型取决于您尝试使用的(un) Tree< t> 马歇尔JSON成。请注意, genericType 是从资源方法签名派生的(对于读者)。例如,对于像这样的方法:
@GET
public String get(final Tree< String> tree){。 ..}
genericType 通用类型信息。但对于像这样的方法:
pre $ @GET
public String get(final Tree tree){...}
Tree 的参数类型应为 Object 。
注意:不要将Java对象封装到JSON中可以使用Jersey中可用的JSON模块并尝试JSON对象的JAXB方法(这里您可以使用 @XmlTransient 注释来省略父母来自(un)编组)。在Jersey 2.3+中,还有一个的概念,它可以让您可以选择将哪些字段视为(未)编组到/从JSON中。
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?
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.
这篇关于通用类的MessageBodyReader / Writer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!