简体   繁体   English

给定一个类,如何获得类序列化的jackson结构?

[英]given a class, how to get the jackson structure of the class serialization?

Given an arbitrary class, is it possible for Jackson to provide a list of the fields needed to serialize and deserialize it? 鉴于任意类,Jackson是否有可能提供序列化和反序列化所需字段的列表?

Jackson's serialization rules are complex. 杰克逊的序列化规则很复杂。 I'd like to determine at runtime what the Jackson JSON structure is expected for an arbitrary class (both serialization and deserialization). 我想在运行时确定Jackson JSON结构对于任意类(序列化和反序列化)的预期。 My current planned implementation is to look for an @JsonConstructor constructor method and parse its arguments. 我当前计划的实现是查找@JsonConstructor构造函数方法并解析其参数。 If that's not there, look for annotations on other methods, and otherwise, use the list of member variables. 如果不存在,请查找其他方法的注释,否则,使用成员变量列表。 I'll recurse the algorithm for any non-primitive field types. 我会为任何非原始字段类型递归算法。

The end goal is to create documentation for service endpoints. 最终目标是为服务端点创建文档。

Yes, you can use Jackson's introspection. 是的,你可以使用杰克逊的内省。 This has the benefit that all annotations are applied as expected, and result should be exactly as Jackson "sees" the type you want information about. 这样做的好处是所有注释都按预期应用,结果应该与杰克逊“看到”您想要了解的类型完全相同。

There are at least two ways to do that: 至少有两种方法可以做到这一点:

  1. Request introspection via SerializationConfig (or, DeserializatonConfig ), to get a BeanDescription 通过SerializationConfig (或DeserializatonConfig )请求内省,以获取BeanDescription
  2. Use callback/visitor based approach by calling ObjectMapper.acceptJsonFormatVisitor(type, visitor) 通过调用ObjectMapper.acceptJsonFormatVisitor(type, visitor)使用基于回调/访问者的方法

First method is usually simpler: 第一种方法通常更简单:

JavaType type = mapper.constructType(MyBean.class);
BeanDescription desc = mapper.getSerializationConfig()
   .introspect(type);

but latter is useful for tasks like generation of schemas (JSON Schema, XML Schema, protoc, thrift). 但后者对于生成模式(JSON Schema,XML Schema,protoc,thrift)等任务非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM