fastjson json 支持注释的问题

qnakjoqk  于 2022-11-13  发布在  其他
关注(0)|答案(3)|浏览(229)

序列化对象时默认不支持,加入某个 SerializerFeature 即可支持序列化是包括注释。
在序列化对象上加个comment的注解,提供注释内容。

使用场景,生成 api 接口文档时使用。

gz5pxeao

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();

}

9nvpjoqh

9nvpjoqh2#

@slf4j
public 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
}

相关问题