Reputation: 983
Following the instructions here, I use the jsonschema2pojo Maven plugin to generate Java classes from JSON example files.
My JSON example file has a structure like this
{
"coffeeTable": {
"book": [
{
"author": "Aldo Rossi",
"title": "The Architecture of the City"
}
]
},
"bookCase": [
{
"book": [
{
"author": "Shakespeare",
"title": "Collected Works"
}
]
}
]
}
When generating Java classes from the JSON example, a class Book
and a class Book__1
is generated. Book
is used for the books on the coffee table. Book__1
is used for the elements in the book case.
I saw that there are solutions for avoiding duplicated classes when generating Java classes with JSON schema files in the documentation.
I did not find a solution when using a JSON object directly for code generation.
Is it possible to achieve that there is only a single Book
class, which is used in both places, generated from the JSON object above? Or do I have to create a JSON schema object from the JSON object and then use the javaType
/existingJavaType
annotation there to achieve this?
Upvotes: 3
Views: 1622
Reputation: 13
What you can do in this case is make 2 separate json schemas and reference one in the other:
room.json
{
"title": "room",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "room.json",
"type": "object",
"properties": {
"coffeeTable": {
"type": "array",
"items": {
"$ref": "book.json"
}
},
"bookCase": {
"type": "array",
"items": {
"$ref": "book.json"
}
}
}
}
and book.json
{
"title": "Book",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "book.json",
"type": "object",
"properties": {
"author": {
"type": "string"
},
"title": {
"type": "string"
}
}
}
This will generate 2 java file: Room.java
& Book.java
Upvotes: 0