如何将JSON有效负载反序列化为基于类型层次结构的特定具体类型,该类型层次结构包括四个端具体类型,每个端具体类型有两个抽象子类型?
子类型可以通过检查JobCallback是否存在“.job”或NotificationCallback是否存在“.notify”来确定。
一旦知道子类型,我们就可以通过查看字段“object.type”的值来确定具体类型。
层次结构包括根抽象类Callback,具有两个抽象子类JobCallback和NotificationCallback,以及四个具体类:DomainJobCallback、TransferJobCallback、DomainNotificationCallback和TransferNotificationCallback。
+-------------------------+
| Callback (abstract) |
+-------------------------+
/-\
/- -\
/-- --\
/- -\
/-- --\
/- -\ <ROOT>.notify != null
<ROOT>.job != null /-- --\
/-- -\
/- --\
/-- -\
/- --\
/-- -\
/- --
+------------------------+ +-----------------------------------+
| JobCallback (abstract) | | NotificationCallback (abstract) |
+------------------------+ +-----------------------------------+
/- / --
/- \- <ROOT>.object.type == "Domain"/- \-
/- \ / \--
/- \- /- \--
<ROOT>.object.type == "Domain" /- \ <ROOT>.object.type == "Transfer" /- \- <ROOT>.object.type = "Transfer"
/- \- / \--
/- \ /- \--
/- \- / \-
/- \ /- \--
/- \- - \-
+-------------------------------+ +--------------------------------+ +--------------------------------------+ +----------------------------------------+
|DomainJobCallback (concrete) | | TransferJobCallback (concrete) | |DomainNotificationCallback (concrete) | | TransferNotificationCallback (concrete)|
+-------------------------------+ +--------------------------------+ +--------------------------------------+ +----------------------------------------+
JSON示例:
- 域名JobCallback *
{
"job": "example-job",
"object": {
"type": "Domain"
}
}
- 调动工作回调 *
{
"job": "example-job",
"object": {
"type": "Transfer"
}
}
- 域名通知回调 *
{
"notify": "example-notify",
"object": {
"type": "Domain"
}
}
- 转账通知回拨 *
{
"notify": "example-notify",
"object": {
"type": "Transfer"
}
}
**方式一:**我最初想到的是回调使用com.fasterxml.Jackson.annotation.JsonTypeInfo.Id#DEDUCTION,JobCallback和NotificationCallback使用com.fasterxml.jackson.annotation.JsonTypeInfo.Id#NAME。然而,我知道覆盖@JsonTypeInfo是不可能的(https://github.com/FasterXML/jackson-databind/issues/3358)。
**方法2:**然后我写了一个自定义的反序列化器,它检查字段.job和.notify的存在,并相应地将工作委托给每个子类型的解析器。我认为从这里开始重用默认解析应该很容易,因为现在我已经确定了子类型,并且我可以查看.object.type的值以获得具体类型,为此我将@JsonTypeInfo和@JsonSubTypes添加到子类型类(JobCallback和NotificationCallback),并返回mapper.treeToValue(node,Callback.JobCallback.class); and mapper.treeToValue(node,Callback.NotificationCallback.class);从parseJobCallback和parseNotificationCallback。这种方法可以被注解掉。
我得到了以下例外:
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class com.example.abc.ex.dm.sm.cf.xyz.schema.Callback$JobCallback]: missing type id property 'object.type'
at [Source: UNKNOWN; line: -1, column: -1]
at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)
at com.fasterxml.jackson.databind.DeserializationContext.missingTypeIdException(DeserializationContext.java:1943)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingTypeId(DeserializationContext.java:1456)
at com.fasterxml.jackson.databind.jsontype.impl.TypeDeserializerBase._handleMissingTypeId(TypeDeserializerBase.java:307)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedUsingDefaultImpl(AsPropertyTypeDeserializer.java:180)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:115)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromAny(AsPropertyTypeDeserializer.java:208)
at com.fasterxml.jackson.databind.JsonDeserializer.deserializeWithType(JsonDeserializer.java:152)
at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:74)
at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:322)
at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:4569)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2798)
at com.fasterxml.jackson.databind.ObjectMapper.treeToValue(ObjectMapper.java:3261)
at com.example.abc.ex.dm.sm.cf.xyz.schema.CallbackDeserializer.parseJobCallback(CallbackDeserializer.java:36)
at com.example.abc.ex.dm.sm.cf.xyz.schema.CallbackDeserializer.deserialize(CallbackDeserializer.java:23)
at com.example.abc.ex.dm.sm.cf.xyz.schema.CallbackDeserializer.deserialize(CallbackDeserializer.java:10)
at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:322)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4593)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3548)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3516)
at com.example.abc.ex.dm.sm.cf.xyz.MyJsonParsingTest.name(MyJsonParsingTest.java:87)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
**方式三:**知道子类型后,解析.object.type的值。
我进一步进行了解析,甚至在知道子类型后提取出具体类型的值。但是,这导致了StackOverflowError。我假设这是进入一个无限循环,因为我调用mapper.treeToValue(node,Callback.JobCallback.DomainJobCallback.class),并且也使用了相同的反序列化器。我知道如果我解析每个字段,然后构造具体的对象,就可以解决这个问题。但我不想手动解析到那个深度。
我也不确定我是否应该像现在这样在CallbackDeserializer中初始化一个对象Map器。
下面是复制此代码的代码:
package com.example.r.e.d.s.c.q;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import org.junit.jupiter.api.Test;
import java.io.IOException;
class MyJsonParsingTest {
private final ObjectMapper objectMapper = new ObjectMapper();
@Test
void test1() throws JsonProcessingException {
String jsonPayload = "{\n" +
" \"job\": \"example-job\",\n" +
" \"object\": {\n" +
" \"type\": \"Domain\"\n" +
" }\n" +
"}\n";
Callback callback = objectMapper.readValue(jsonPayload, Callback.class);
System.out.println("callback = " + callback);
}
public static class CallbackDeserializer extends JsonDeserializer<Callback> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public Callback deserialize(final JsonParser jsonParser,
final DeserializationContext deserializationContext) throws IOException {
final JsonNode node = jsonParser.getCodec().readTree(jsonParser);
final JsonNode jobCallbackNode = node.get("job");
final JsonNode notificationCallbackNode = node.get("notify");
if (jobCallbackNode != null) {
return parseJobCallback(node, jsonParser);
}
else if (notificationCallbackNode != null) {
return parseNotificationCallback(node, jsonParser);
}
else {
throw InvalidDefinitionException.from(jsonParser, "Invalid callback type", (JavaType) null);
}
}
private Callback parseJobCallback(final JsonNode node,
final JsonParser jsonParser) throws IOException {
// return mapper.treeToValue(node, Callback.JobCallback.class);
final String type = node.get("object").get("type").asText();
if (type.equals("Domain")) {
return mapper.treeToValue(node, Callback.JobCallback.DomainJobCallback.class);
}
else if (type.equals("Transfer")) {
return mapper.treeToValue(node, Callback.JobCallback.TransferJobCallback.class);
}
throw InvalidDefinitionException.from(jsonParser, "Invalid job callback type", (JavaType) null);
}
private Callback parseNotificationCallback(final JsonNode node,
final JsonParser jsonParser) throws JsonProcessingException {
// return mapper.treeToValue(node, Callback.NotificationCallback.class);
final String type = node.get("object").get("type").asText();
if (type.equals("Domain")) {
return mapper.treeToValue(node, Callback.NotificationCallback.DomainNotificationCallback.class);
}
else if (type.equals("Transfer")) {
return mapper.treeToValue(node, Callback.NotificationCallback.TransferNotificationCallback.class);
}
throw InvalidDefinitionException.from(jsonParser, "Invalid job callback type", (JavaType) null);
}
}
@JsonDeserialize(using = CallbackDeserializer.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract static class Callback {
private Obj object;
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "object.type")
// @JsonSubTypes({
// @JsonSubTypes.Type(value = JobCallback.DomainJobCallback.class, name = "Domain"),
// @JsonSubTypes.Type(value = JobCallback.TransferJobCallback.class, name = "Transfer"),
// })
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract static class JobCallback extends Callback {
private String job;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class DomainJobCallback extends Callback.JobCallback {
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TransferJobCallback extends Callback.JobCallback {
}
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "object.type")
// @JsonSubTypes({
// @JsonSubTypes.Type(value = NotificationCallback.DomainNotificationCallback.class, name = "Domain"),
// @JsonSubTypes.Type(value = NotificationCallback.TransferNotificationCallback.class, name = "Contact")
// })
@JsonIgnoreProperties(ignoreUnknown = true)
public static class NotificationCallback extends Callback {
private String notify;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class DomainNotificationCallback extends NotificationCallback {
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TransferNotificationCallback extends NotificationCallback {
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Obj {
private String type;
}
}
}
1条答案
按热度按时间4bbkushb1#
我认为您需要配置
ObjectMapper
使用基于字段的序列化(默认为基于bean的序列化,即。它查找getter/setter)。我还发现模块比注解更容易工作。例如:如果我运行它,我会得到以下结果,这表明它已经成功Map了JSON: