您可以使用StdSerializer编写/尝试自定义序列化程序。
CustomJsonSerializer示例。注意:没有运行代码。
public class CustomJsonSerializer extends StdSerializer<AbstractEntity> {
public CustomJsonSerializer() {
this(null);
}
public CustomJsonSerializer(Class<AbstractEntity> t) {
super(t);
}
@Override
public void serialize(AbstractEntity value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
Field[] fields = value.getClass().getDeclaredFields();
jgen.writeStartObject();
for (Field field : fields) {
field.setAccessible(true);
try {
// Do the proper field mapping for field types . Object type example
jgen.writeObjectField(field.getName(), field.get(value));
} catch (Exception e) {
// catch error
}
}
jgen.writeEndObject();
}
}
然后在Rest方法中使用@JsonSerialize
@JsonSerialize(using = CustomJsonSerializer.class)
@GetMapping(path="/all", produces = "application/json; charset=UTF-8", headers = "Accept=application/json")
public @ResponseBody Iterable<User> getAllUsers() {
return repositoryUser.findAll();
}
请看
Custom Serializer
和
StdSerializer
可能的不同解决方案
jackson-bidirectional infinite-recursion