我试图记录我的JSON API。我的API返回由Jackson序列化的Java POJO。我正在编写服务以返回每个服务的示例JSON。我想做的是这样的事情:
class MyPojo {
@Example("Bob")
public String name;
@Example(42)
public Integer myInt;
public String noExample;
}
我需要一些方法让杰克逊将其序列化为:
{
"name": "Bob",
"myInt": 42
"noExample": "string"
}
当我需要一个例子时。
实现这一目标的最简单方法是什么?
答案 0 :(得分:2)
您可以考虑使用ObjectMapper.acceptJsonFormatVisitor
方法来访问bean类的元信息。 the Jackson JSON schema module中使用了类似的方法来生成模式。
这是一个展示这个想法的例子:
public class JacksonSchema1 {
@Retention(RetentionPolicy.RUNTIME)
public static @interface Example {
String value();
}
public static class MyPojo {
@Example("Bob")
public String name;
@Example("42")
public Integer myInt;
public String noExample;
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
MyJsonFormatVisitorWrapper visitor = new MyJsonFormatVisitorWrapper(mapper);
mapper.acceptJsonFormatVisitor(MyPojo.class, visitor);
System.out.println(mapper.writeValueAsString(visitor.getExample()));
}
private static class MyJsonFormatVisitorWrapper implements JsonFormatVisitorWrapper {
private final ObjectMapper mapper;
private final Map<String, Object> example = new LinkedHashMap<>();
private MyJsonFormatVisitorWrapper(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public JsonObjectFormatVisitor expectObjectFormat(JavaType type) throws JsonMappingException {
return new JsonObjectFormatVisitor.Base() {
@Override
public void optionalProperty(BeanProperty prop) throws JsonMappingException {
Example a = prop.getAnnotation(Example.class);
if (a != null) {
example.put(prop.getName(), mapper.convertValue(a.value(), prop.getType()));
} else {
example.put(prop.getName(), prop.getType().toCanonical());
}
}
};
}
@Override
public JsonArrayFormatVisitor expectArrayFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public JsonStringFormatVisitor expectStringFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public JsonNumberFormatVisitor expectNumberFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public JsonIntegerFormatVisitor expectIntegerFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public JsonBooleanFormatVisitor expectBooleanFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public JsonNullFormatVisitor expectNullFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public JsonAnyFormatVisitor expectAnyFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public JsonMapFormatVisitor expectMapFormat(JavaType type) throws JsonMappingException {
return null;
}
@Override
public SerializerProvider getProvider() {
return null;
}
@Override
public void setProvider(SerializerProvider provider) {
}
public Map<String,Object> getExample() {
return example;
}
}
}
输出:
{"name":"Bob","myInt":42,"noExample":"java.lang.String"}