1. 概述
在某些情况下,我们需要使用JSON 文件创建Java 类,也称为POJO。这是可能的,而无需使用方便的**
在本教程中,我们将看到如何使用此库从JSON 对象创建Java 类。
2. 设置
jsonschema2pojo-core
<dependency> <groupId>org.jsonschema2pojo</groupId> <artifactId>jsonschema2pojo-core</artifactId> <version>1.1.1</version> </dependency>
3. JSON 到Java 类的转换
让我们看看如何使用jsonschema2pojo
首先,我们将创建一个方法convertJsonToJavaClass
一个
inputJson将生成POJO 的
outputJavaClassDirectoryPOJO 类所属的
packageName输出POJO
className
然后,我们将定义此方法中的步骤:
我们将从创建
JCodeModel然后,我们将定义
jsonschema2pojogetSourceType此外,我们将此配置传递给
RuleFactory我们将使用这个工厂和
SchemaGeneratorSchemaMapper最后,我们将调用
JCodeModelbuild
让我们看看实现:
public void convertJsonToJavaClass(URL inputJsonUrl, File outputJavaClassDirectory, String packageName, String javaClassName)
throws IOException {
JCodeModel jcodeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() { @Override
public boolean isGenerateBuilders() { return true;
}
@Override
public SourceType getSourceType() { return SourceType.JSON;
}
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(jcodeModel, javaClassName, packageName, inputJsonUrl);
jcodeModel.build(outputJavaClassDirectory);
}4. 输入和输出
让我们使用这个示例JSON 来执行程序:
{ "name": "1ju.org", "area": "tech blogs", "author": "Eugen", "id": 32134, "topics": [ "java", "kotlin", "cs", "linux"
],
"address": { "city": "Bucharest", "country": "Romania"
}
}执行程序后,它会在给定目录中创建以下Java 类:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"name", "area", "author", "id", "topics", "address"})
@Generated("jsonschema2pojo")
public class Input {
@JsonProperty("name")
private String name; @JsonProperty("area")
private String area; @JsonProperty("author")
private String author; @JsonProperty("id")
private Integer id; @JsonProperty("topics")
private List<String> topics = new ArrayList<String>(); @JsonProperty("address")
private Address address; @JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
// getters & setters
// hashCode & equals
// toString
}**请注意,它因此也为嵌套的JSON 对象Address
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"city", "country"})
@Generated("jsonschema2pojo")
public class Address {
@JsonProperty("city")
private String city; @JsonProperty("country")
private String country; @JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
// getters & setters
// hashCode & equals
// toString
}我们也可以通过简单地访问 工具采用JSON(或YAML)模式文档并生成DTO 样式的Java 类。它提供了许多您可以选择包含在Java 类中的选项,包括构造函数以及jsonschema2pojohashCode, equals,toString
0 评论