避免使用 jsonschema2pojo 和 sourceType "json" 生成重复的类

问题描述 投票:0回答:2

按照此处的说明,我使用 jsonschema2pojo Maven 插件从 JSON 示例文件生成 Java 类。

我的 JSON 示例文件具有这样的结构

{ "coffeeTable": { "book": [ { "author": "Aldo Rossi", "title": "The Architecture of the City" } ] }, "bookCase": [ { "book": [ { "author": "Shakespeare", "title": "Collected Works" } ] } ] }
从 JSON 示例生成 Java 类时,会生成一个类 

Book

 和一个类 
Book__1
Book
 用于咖啡桌上的书籍。 
Book__1
 用于书柜中的元素。
我看到在
使用文档中的 JSON 模式文件生成 Java 类时有避免重复类的解决方案。 直接使用JSON对象进行代码生成时我没有找到解决方案。 是否可以实现只有一个 Book
 类,在两个地方都使用,由上面的 JSON 对象生成?或者我是否必须从 JSON 对象创建一个 JSON 模式对象,然后使用 
javaType
/
existingJavaType
 注释来实现此目的?

java json maven jsonschema2pojo
2个回答
0
投票
在这种情况下,您可以做的是创建 2 个单独的 json 模式,并在另一个中引用一个模式:

房间.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" } } } }
和 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" } } }
这将生成 2 个 java 文件: 

Room.java

 & 
Book.java

    


0
投票
我最近也遇到了同样的问题。

您可以引用已经创建的类来避免__1等。
例如:

而不是这个:

... "orderTotalPrice": [ { "name": "string", "priceType": "string", "recurringChargePeriod": "string", "unitOfMeasure": "string", "price": { -> DEFINED ONCE "taxIncludedAmount": { "unit": "string", "value": 0 } } } ], "productOrderItem": [ { "id": "string", "quantity": "string", "action": "string", "itemPrice": [ { "description": "string", "name": "string", "priceType": "string", "recurringChargePeriod": "string", "unitOfMeasure": "string", "price": { -> DEFINED TWICE "taxIncludedAmount": { "unit": "string", "value": 0 } } } ] ...
你可以做到这一点

... "orderTotalPrice": [ { "name": "string", "priceType": "string", "recurringChargePeriod": "string", "unitOfMeasure": "string", "price": { -> DEFINED ONCE "taxIncludedAmount": { "unit": "string", "value": 0 } } } ], "productOrderItem": [ { "id": "string", "quantity": "string", "action": "string", "itemPrice": [ { "description": "string", "name": "string", "priceType": "string", "recurringChargePeriod": "string", "unitOfMeasure": "string", "price": "com.xyz.wyt.Price" -> REUSED } ] ...
    
© www.soinside.com 2019 - 2024. All rights reserved.