Как сериализовать классы из JSON с конструкцией any
Почему не сериализуются классы из объектов в "anyOf"? Есть например json-схема:
{
"type":"object",
"properties": {
"foo": {
"anyOf": [
{"$ref": "#/definitions/Template"},
{"$ref": "#/definitions/Limit"}
]
}
},
"definitions": {
"Template": {
"type": "object",
"properties": {
"age": {
"type": "string"
},
"name": {
"type": "string"
}
}
},
"Limit": {
"type": "object",
"properties": {
"petName": {
"type": "string"
},
"hunts": {
"type": boolean
}
}
}
}
}
Сериализуем с помощью библиотеки http://www.jsonschema2pojo.org/ Получаем:
package com.example;
import java.util.HashMap;
import java.util.Map;
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;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"foo"
})
public class Example {
@JsonProperty("foo")
private Object foo;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("foo")
public Object getFoo() {
return foo;
}
@JsonProperty("foo")
public void setFoo(Object foo) {
this.foo = foo;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Почему не формируются классы Template, Limit? Как поступать с такими схемами для сериализации?
Ответы (1 шт):
Автор решения: Aziz Umarov
→ Ссылка
У Вас проблема в
"hunts": {
"type": boolean
}
Попробуйте так.
{
"type":"object",
"properties": {
"foo": {
"anyOf": [
{"$ref": "#/definitions/Template"},
{"$ref": "#/definitions/Limit"}
]
}
},
"definitions": {
"Template": {
"type": "object",
"properties": {
"age": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
},
"Limit": {
"type": "object",
"properties": {
"petName": {
"type": "string"
},
"hunts": {
"type": "boolean"
}
}
}
}
UPD
Так можно получить если foo конкретного типа
{
"type":"object",
"properties": {
"foo":
{"$ref": "#/definitions/Template"}
},
"definitions": {
"Template": {
"type": "object",
"properties": {
"age": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
},
"Limit": {
"type": "object",
"properties": {
"petName": {
"type": "string"
},
"hunts": {
"type": "boolean"
}
}
}
}