英文:
Json schema with anyOf field with same name and different types to POJO + Jackson
问题
如果有一个包含AnyOf部分的组件A的架构,其中包含两个条目。它们之间的区别在于,在一种情况下,子组件C是数组,在另一种情况下,C是对象,但它们具有相同的名称B。如果我为此在Java中有两个对象,是否可能使用Jackson处理它呢?
我在思考是否可以使用带有某些注解的接口,然后Jackson将确定正确的对象...
"A": {
"type": "object",
"anyOf": [
{
"properties": {
"B": {
"type": "array",
"items": {
"type": "object",
"$ref": "#/components/schemas/C"
}
}
},
"additionalProperties": false
},
{
"properties": {
"B": {
"type": "object",
"$ref": "#/components/schemas/C"
}
},
"additionalProperties": false
}
]
}
假设我在Java中有这样的代码:
public class AAnyOf1 {
@JsonProperty("B")
private List
...
}
public class AAnyOf2 {
@JsonProperty("B")
private C b = null;
...
}
<details>
<summary>英文:</summary>
If have a schema with component A that contains AnyOf section with two items. The difference between them is that in one case child component C is array and in another one C is object but they have the same name B. Is it possible to handle it with jackson if I have two java objects for that?
I'm thinking if I can use interface with some annotations and jackson will determine the correct object...
"A": {
"type": "object",
"anyOf": [
{
"properties": {
"B": {
"type": "array",
"items": {
"type": "object",
"$ref": "#/components/schemas/C"
}
}
},
"additionalProperties": false
},
{
"properties": {
"B": {
"type": "object",
"$ref": "#/components/schemas/C"
}
},
"additionalProperties": false
}
]
}
Lets suppose I have this in java
public class AAnyOf1 {
@JsonProperty("B")
private List<C> b = new ArrayList<>();
...
}
public class AAnyOf2 {
@JsonProperty("B")
private C b = null;
...
}
</details>
# 答案1
**得分**: 1
这是一种非常流行的模式,用于在响应中发送一个`JSON对象`,而不是带有一个`JSON对象`的`JSON数组`。因此,替代方式如下:
{
"b": {
"id": 1
}
}
`API`响应如下:
{
"b": {
"id": 1
}
}
`Jackson`已经处理了这种用例。您需要启用[ACCEPT_SINGLE_VALUE_AS_ARRAY][1]特性,并且只需要一个版本的`POJO`:
```java
class AAnyOf {
@JsonProperty("B")
private List<C> b;
...
}
英文:
This is very popular pattern to send in response a JSON Object
instead of JSON Array
with one JSON Object
. So, instead of:
{
"b": [
{
"id": 1
}
]
}
API
response looks like:
{
"b": {
"id": 1
}
}
Jackson
already handle this use case. You need to enable ACCEPT_SINGLE_VALUE_AS_ARRAY feature and you need only one version of POJO
:
class AAnyOf {
@JsonProperty("B")
private List<C> b;
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论