从POJO生成Json模式 [英] Generate Json Schema from POJO with a twist

查看:118
本文介绍了从POJO生成Json模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有什么:



我正在从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));

我通过上述代码生成多个模式。其中一个pojos有一个内部嵌入式枚举来限制可能的值,如下所示:

  public class MyClass {

@JsonProperty(name)
private String name;
@JsonProperty(startDayOfWeek)
private MyClass.StartDayOfWeek startDayOfWeek;
/ **
*由时区路线返回的时区的ID。
*
* /
@JsonProperty(timezone)
private String timezone;
@JsonIgnore
private Map< String,Object> additionalProperties = new HashMap< String,Object>();

/ **
*
* @return
* startDayOfWeek
* /
@JsonProperty(startDayOfWeek)
public MyClass.StartDayOfWeek getStartDayOfWeek(){
return startDayOfWeek;
}

/ **
*
* @param startDayOfWeek
* startDayOfWeek
* /
@JsonProperty( startDayOfWeek)
public void setStartDayOfWeek(MyClass.StartDayOfWeek startDayOfWeek){
this.startDayOfWeek = startDayOfWeek;
}

public static enum StartDayOfWeek {

MONDAY(Monday),
TUESDAY(Tuesday),
WEDNESDAY 星期三),
THURSDAY(星期四),
FRIDAY(星期五),
SATURDAY(星期六),
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数据中的可能的String值限制在

当我在有问题的代码上运行模式生成器时,我希望得到以下模式:

  
type:object,
javaType:my.package.MyClass,
properties:{
startDayOfWeek:{
type:string,
enum:[星期一,星期二,星期三,星期四,星期五
}
}

而是我得到这个:

  {
type:object,
id:urn:jsonschema:my:package :
title:Lmy / package / MyClass,
properties:{
startDayOfWeek:{
type:string
}
}
}

我已经在Jackson Schema Module源代码中进行了一些挖掘,并且发现发生了什么事情是Jackson的使用.toString )作为枚举类型的默认序列化方法,但是我需要做的是创建基于 StartDayOfWeek.values()的行: p

 枚举:[星期一,星期二,星期三,星期四 ,星期天] 

有谁知道该怎么做?

解决方案

Storme的回答引用 org.codehaus ,这是一个较旧的杰克逊版本。以下是类似的,但是使用了quickxml(较新版本)。



Pom:

 <依赖性> 
< groupId> com.fasterxml.jackson.core< / groupId>
< artifactId> jackson-core< / artifactId>
< version> 2.7.1< / version>
< / dependency>
<依赖关系>
< groupId> com.fasterxml.jackson.core< / groupId>
< artifactId> jackson-databind< / artifactId>
< version> 2.7.1< / version>
< / dependency>
<依赖关系>
< groupId> com.fasterxml.jackson.core< / groupId>
< artifactId> jackson-annotations< / artifactId>
< version> 2.7.1< / version>
< / dependency>
<依赖关系>
< groupId> com.fasterxml.jackson.module< / groupId>
< artifactId> jackson-module-jsonSchema< / artifactId>
< version> 2.1.0< / version>
< / dependency>

代码:

 code> import ... TargetClass; 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsonschema.JsonSchema;

import java.io.IOException;

public final class JsonSchemaGenerator {

private JsonSchemaGenerator(){};

public static void main(String [] args)throws IOException {
System.out.println(JsonSchemaGenerator.getJsonSchema(TargetClass.class));
}

public static String getJsonSchema(Class clazz)throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING,true);
JsonSchema schema = mapper.generateJsonSchema(clazz);
return mapper.writerWithDefaultPrettyPrinter()。writeValueAsString(schema);
}

}


What I have:

I'm generating a JSON schema from a pojo. My code to generate the schema looks like so:

ObjectMapper mapper = new ObjectMapper();
TitleSchemaFactoryWrapper visitor = new TitleSchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema schema = visitor.finalSchema();
schemas.put(clazz, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));

I'm generating several schemas via the above code. One of the pojos has an internal embedded enum to limit the possible values, like so:

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;
            }
        }

    }

}

The above code should limit the possible String values in the JSON data that's passed around to "Monday", "Tuesday", "Wednesday", etc.

When I run the schema generator on the code in question, I expect to get something like the following schema:

{
  "type" : "object",
  "javaType" : "my.package.MyClass",
  "properties": {
    "startDayOfWeek" : {
      "type" : "string",
      "enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]
    }
  }
}

but instead I'm getting this:

{
  "type" : "object",
  "id" : "urn:jsonschema:my:package:MyClass",
  "title" : "Lmy/package/MyClass;",
  "properties" : {
    "startDayOfWeek" : {
      "type" : "string"
    }
  }
}

I've done some digging in the Jackson Schema Module source code and figured out that what's happening is Jackson's using ".toString()" as the default serialization method for enum types, but what I need it to do instead is create the line that looks like this based on StartDayOfWeek.values():

"enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]

Does anyone know how to do that?

解决方案

Storme's answer references org.codehaus, which is an older version of jackson. The following is similar but uses fasterxml (newer version).

Pom:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.7.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-jsonSchema</artifactId>
    <version>2.1.0</version>
</dependency>

Code:

import ...TargetClass;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsonschema.JsonSchema;

import java.io.IOException;

public final class JsonSchemaGenerator {

    private JsonSchemaGenerator() { };

    public static void main(String[] args) throws IOException {
        System.out.println(JsonSchemaGenerator.getJsonSchema(TargetClass.class));
    }

    public static String getJsonSchema(Class clazz) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        JsonSchema schema = mapper.generateJsonSchema(clazz);
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
    }

}

这篇关于从POJO生成Json模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆