我有的:
我正在从 pojo 生成 JSON 模式。我生成架构的代码如下所示:
ObjectMapper mapper = new ObjectMapper();
TitleSchemaFactoryWrapper visitor = new TitleSchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema schema = visitor.finalSchema();
schemas.put(clazz, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));
我通过上面的代码生成了几个模式。其中一个 pojo 有一个内部嵌入的枚举来限制可能的值,如下所示:
public class MyClass {
@JsonProperty("name")
private String name;
@JsonProperty("startDayOfWeek")
private MyClass.StartDayOfWeek startDayOfWeek;
/**
* The ID of a timezone returned by the timezones route.
*
*/
@JsonProperty("timezone")
private String timezone;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The startDayOfWeek
*/
@JsonProperty("startDayOfWeek")
public MyClass.StartDayOfWeek getStartDayOfWeek() {
return startDayOfWeek;
}
/**
*
* @param startDayOfWeek
* The startDayOfWeek
*/
@JsonProperty("startDayOfWeek")
public void setStartDayOfWeek(MyClass.StartDayOfWeek startDayOfWeek) {
this.startDayOfWeek = startDayOfWeek;
}
public static enum StartDayOfWeek {
MONDAY("Monday"),
TUESDAY("Tuesday"),
WEDNESDAY("Wednesday"),
THURSDAY("Thursday"),
FRIDAY("Friday"),
SATURDAY("Saturday"),
SUNDAY("Sunday");
private final String value;
private static Map<String, MyClass.StartDayOfWeek> constants = new HashMap<String, MyClass.StartDayOfWeek>();
static {
for (MyClass.StartDayOfWeek c: values()) {
constants.put(c.value, c);
}
}
private StartDayOfWeek(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
@JsonCreator
public static MyClass.StartDayOfWeek fromValue(String value) {
MyClass.StartDayOfWeek constant = constants.get(value);
if (constant == null) {
throw new IllegalArgumentException(value);
} else {
return constant;
}
}
}
}
上面的代码应该限制传递到“星期一”、“星期二”、“星期三”等的 JSON 数据中可能的字符串值。
当我在相关代码上运行模式生成器时,我希望得到类似于以下模式的内容:
{
"type" : "object",
"javaType" : "my.package.MyClass",
"properties": {
"startDayOfWeek" : {
"type" : "string",
"enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]
}
}
}
但相反,我得到了这个:
{
"type" : "object",
"id" : "urn:jsonschema:my:package:MyClass",
"title" : "Lmy/package/MyClass;",
"properties" : {
"startDayOfWeek" : {
"type" : "string"
}
}
}
我已经在 Jackson Schema Module 源代码中进行了一些挖掘,并发现正在发生的事情是 Jackson 使用“.toString()”作为枚举类型的默认序列化方法,但我需要它做的是创建行看起来像这样基于StartDayOfWeek.values()
:
"enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]
有谁知道这是怎么做到的吗?