序列化对象时默认不支持,加入某个 SerializerFeature 即可支持序列化是包括注释。在序列化对象上加个comment的注解,提供注释内容。
使用场景,生成 api 接口文档时使用。
gz5pxeao1#
public class FieldCommentFilter extends BeforeFilter {
@Override public void writeBefore(Object object) { Field[] fields = object.getClass().getDeclaredFields(); if (fields == null) { return; } for (Field field : fields) { JsonComment jsonComment = field.getAnnotation(JsonComment.class); if (jsonComment == null) { continue; } String key = field.getName() + "Comment"; String value = jsonComment.desc(); writeKeyValue(key, value); } }
}
@target(ElementType.FIELD)@retention(RetentionPolicy.RUNTIME)public @interface JsonComment {
// 描述 String desc();
9nvpjoqh2#
@slf4jpublic class FieldCommentFilter implements ValueFilter {
@Override public Object process(Object object, String name, Object value) { Field field = null; try { field = object.getClass().getDeclaredField(name); } catch (Exception ex) { log.info("解析 field 失败", ex); } if (field == null) { return value; } JsonComment jsonComment = field.getAnnotation(JsonComment.class); if (jsonComment == null) { return value; } return formatComment(field, jsonComment, value); } private Map<String, Object> formatComment(@NonNull Field field, @NonNull JsonComment jsonComment, Object value) { String desc = jsonComment.desc(); boolean required = jsonComment.required(); Map<String, Object> extraMap = new LinkedHashMap<>(); extraMap.put("类型", field.getType().getName()); extraMap.put("默认值", value == null ? "" : String.valueOf(value)); extraMap.put("描述", desc); if (required) { extraMap.put("是否必填", "是"); } return extraMap; }
{"code":200,"error":null,"result":[{"id":0,"name":{"类型":"java.lang.String","默认值":"","描述":"姓名"},"status":{"类型":"int","默认值":"2","描述":"1:未审核,2:已审核","是否必填":"是"}},{"id":0,"name":{"类型":"java.lang.String","默认值":"","描述":"姓名"},"status":{"类型":"int","默认值":"2","描述":"1:未审核,2:已审核","是否必填":"是"}} ],"success":true}
68bkxrlz3#
@wenshao
3条答案
按热度按时间gz5pxeao1#
public class FieldCommentFilter extends BeforeFilter {
}
@target(ElementType.FIELD)
@retention(RetentionPolicy.RUNTIME)
public @interface JsonComment {
}
9nvpjoqh2#
@slf4j
public class FieldCommentFilter implements ValueFilter {
}
{
"code":200,
"error":null,
"result":[
{
"id":0,
"name":{
"类型":"java.lang.String",
"默认值":"",
"描述":"姓名"
},
"status":{
"类型":"int",
"默认值":"2",
"描述":"1:未审核,2:已审核",
"是否必填":"是"
}
},
{
"id":0,
"name":{
"类型":"java.lang.String",
"默认值":"",
"描述":"姓名"
},
"status":{
"类型":"int",
"默认值":"2",
"描述":"1:未审核,2:已审核",
"是否必填":"是"
}
}
],
"success":true
}
68bkxrlz3#
@wenshao