jsonschema2pojo 的 customAnnotator 允许我向生成的 java 文件添加自定义注释。它的烦恼是您的注释器类必须在一个单独的项目中,并且必须包含在插件中。这就是为什么。
将依赖项添加到您的 pom.xml
<dependency>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-core</artifactId>
<version>0.4.0</version>
</dependency>
将插件添加到 pom.xml 插件
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>0.5.1</version>
<dependencies>
<!-- NOTE: Your annotator MUST come from a dependency -->
<dependency>
<groupId>ANNOTATOR_GROUP_ID</groupId>
<artifactId>ANNOTATOR_ARTIFACT</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>compile</scope>
<version>1.5.2.RELEASE</version>
</dependency>
<!-- NOTE: Any annotation used must have its dependency here!!! -->
</dependencies>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>com.test.gen</targetPackage>
<useCommonsLang3>true</useCommonsLang3>
<customAnnotator>com.fully.qualified.path.YourAnnotator</customAnnotator>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
在单独的项目中创建您的自定义注释器类。
package com.deere.gtin_k.pdeaas.work_manager.application;
import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JFieldVar;
import org.jsonschema2pojo.AbstractAnnotator;
import javax.persistence.Entity;
public class HibernateAnnotator extends AbstractAnnotator {
@Override
public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
super.propertyField(field, clazz, propertyName, propertyNode);
// Note: does not have to be the propertyName, could be the field or propertyNode that is verified.
if (propertyName.equals("entity")) {
clazz.annotate(Entity.class);
}
}
}
最后,json文件:
{
"title": "Person",
"type": "object",
"properties": {
"entity": true,
"name": {
"type": "string"
}
}
}
最后的结果:
package com.test.gen;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Entity;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Person
* <p>
*
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Entity
@JsonPropertyOrder({
"entity",
"name"
})
public class Person {
@JsonProperty("entity")
private Object entity;
...
}
我希望有一种更简单的方法来做到这一点。