Невозможно десериализовать общую иерархию классов, используя Джексона
Я получаю, например, этот JSON от внешнего поставщика (где payload
может быть переменной):
{
"payload": {
"enrolledAt": "2018-11-05T00:00:00-05:00",
"userId": "99c7ff5c-2c4e-423f-abeb-2e5f3709a42a"
},
"requestId": "80517bb8-2a95-4f15-9a73-fcf3752a1147",
"eventType": "event.success",
"createdAt": "2018-11-05T16:55:13.762-05:00"
}
Я пытаюсь смоделировать их, используя этот класс:
public final class Notification<T extends AbstractModel> {
@JsonProperty("requestId")
private String requestId;
@JsonProperty("eventType")
private String eventType;
@JsonProperty("createdAt")
private ZonedDateTime createdAt;
private T payload;
@JsonCreator
public Notification(@JsonProperty("payload") T payload) {
requestId = UUID.randomUUID().toString();
eventType = payload.getType();
createdAt = ZonedDateTime.now();
this.payload = payload;
}
// getters
}
... и затем иметь эти возможные (общие) типы:
public abstract class AbstractModel {
private String userId;
private Type type;
@JsonCreator
AbstractModel(@JsonProperty("companyUserId") String userId, @JsonProperty("type") Type type) {
this.userId = userId;
this.type = type;
}
// getters
public enum Type {
CANCEL("event.cancel"),
SUCCESS("event.success");
private final String value;
Type(String value) {
this.value = value;
}
public String getValue() { return value; }
}
}
public final class Success extends AbstractModel {
private ZonedDateTime enrolledAt;
@JsonCreator
public Success(String userId, @JsonProperty("enrolledAt") ZonedDateTime enrolledAt) {
super(userId, Type.SUCCESS);
this.enrolledAt = enrolledAt;
}
// getters
}
public final class Cancel extends AbstractModel {
private ZonedDateTime cancelledAt;
private String reason;
@JsonCreator
public Cancel(String userId, @JsonProperty("cancelledAt") ZonedDateTime cancelledAt,
@JsonProperty("reason") String reason) {
super(userId, Type.CANCEL);
this.cancelledAt = cancelledAt;
this.reason = reason;
}
// getters
}
Приложение основано на Spring Boot, поэтому я десериализирую JSON следующим образом:
@Component
public final class NotificationMapper {
private ObjectMapper mapper;
public NotificationMapper(final ObjectMapper mapper) {
this.mapper = mapper;
}
public Optional<Notification<? extends AbstractModel>> deserializeFrom(final String thiz) {
try {
return Optional.of(mapper.readValue(thiz, new NotificationTypeReference()));
} catch (final Exception e) { /* log errors here */ }
return Optional.empty();
}
private static final class NotificationTypeReference extends TypeReference<Notification<? extends AbstractModel>> { }
}
... но в конце концов, так как я публикую это прямо здесь, Джексону пока что это не нравится. Я пробовал несколько вещей, таких как: JsonTypeInfo
а также JsonSubTypes
, но я не могу изменить ввод JSON.
Кто-нибудь? Любая подсказка (и)?
0 ответов
Мы закончили тем, что добавили еще одну пару ключ / значение в JSON - контракт действительно был немного изменен, чтобы приспособить эту "приватную" пару ключ / значение.
В любом случае, если кто-то столкнется с той же проблемой, это решение для подхода:
...
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonIgnoreProperties("_type")
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "_type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Cancel.class, name = "_type"),
@JsonSubTypes.Type(value = Fail.class, name = "_type"),
@JsonSubTypes.Type(value = Success.class, name = "_type"),
})
public abstract class AbstractModel {
private String userId;
private Type type;
AbstractModel() { }
AbstractModel(final String userId, final Type type) {
this.userId = userId;
this.type = type;
}
// getters, toString, etc.
public enum Type {
CANCEL("event.cancelled"),
FAIL("event.failed"),
SUCCESS("event.success");
private final String value;
Type(String value) {
this.value = value;
}
public String getValue() { return value; }
}
}