jackson databind如何将java注释的属性和值输出为JSON格式?
我已经定义了注释,并在Java接口上使用它,我的代码是:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface ThingPropertyDefinition {
String identifier();
String name() default "";
EnumDataType dataType();
EnumReadWrite rw();
String description() default "";
ConstraintDefinition constraint() default @ConstraintDefinition();
boolean isScene() default true;
boolean isRequired() default true;
}
使用界面上的注释,我的代码:
@ThingService(name = "SmartGateway")
public interface ISmartGatewayService extends IThingService {
//==================define properties==================
/**
* node
*/
@ThingPropertyDefinition(identifier = "Nodes",
name = "节点列表",
description = "网关当前管理的节点列表",
dataType = EnumDataType.STRUCT,
rw = EnumReadWrite.READ_ONLY,
constraint = @ConstraintDefinition(unit = EnumUnit.UNKNOWN),
isRequired = true)
List<ThingDeviceNode> nodes = new ArrayList<>();
//...
}
并使用java反射输出JSON格式
Map<String, Map<String, List<Annotation>>> clazzAnnotation = new ConcurrentHashMap<>();
cacheClassMap.entrySet()
.parallelStream()
.forEachOrdered((clazz) -> {
List<Annotation> props = new ArrayList<>();
List<Annotation> actions = new ArrayList<>();
List<Annotation> events = new ArrayList<>();
Field[] fields = clazz.getValue().getFields();
Stream.of(fields).forEach((f) -> {
f.setAccessible(true);
Arrays.stream(f.getAnnotations()).forEach((a) -> {
if (a.annotationType().equals(ThingPropertyDefinition.class)) {
props.add(a);
}
});
});
Method[] methods = clazz.getValue().getMethods();
Stream.of(methods).forEach((m) -> {
m.setAccessible(true);
Arrays.stream(m.getDeclaredAnnotations()).forEach((a) -> {
if (a.annotationType().equals(ThingActionDefinition.class)) {
actions.add(a);
}
if (a.annotationType().equals(ThingEventDefinition.class)) {
events.add(a);
}
});
});
Map<String, List<Annotation>> model = new ConcurrentHashMap<>();
model.put("actions", actions);
model.put("events", events);
model.put("properties", props);
clazzAnnotation.put(clazz.getKey(), model);
});
ObjectMapper mapper = new ObjectMapper();
//TODO!
log.debug("{}", mapper.writeValueAsString(clazzAnnotation));
我使用jackson mapper对象输出列表,但输出不是完整的,如下所示:
"home.gateway.ISmartGatewayService": {
"actions": [
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
},
{
"required": true
}
],
"events": [
{},
{},
{},
{},
{},
{},
{}
],
"properties": [
{
"required": true,
"scene": true
}
]
},
如何将注释的所有属性和值输出?我测试fastjson,它可以工作,有人有想法吗
共 (0) 个答案