根据字段的存在以及另一个字段的值来反序列化JSON。

huangapple go评论62阅读模式
英文:

Deserializing JSON based on the presence of fields and based on the value of another field

问题

Here's the translated code portion:

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.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 = "{
            \"job\": \"example-job\",
            \"object\": {
                \"type\": \"Domain\"
            }
        }";

        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 {

            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 {

            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;

        @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 {

        }

        @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;

        }
    }
}

Please note that I have translated the code you provided, but if you have any specific questions or need further assistance, please let me know.

英文:

How can I deserialize JSON payloads into specific concrete types based on a hierarchy of types that includes four end concrete types, each with two abstract sub-types?

The sub-type can be determined by checking for the presence of either ".job" for JobCallback or ".notify" for NotificationCallback.

Once the sub-type is known, we can determine the concrete type by looking at the value of the field "object.type".

The hierarchy includes a root abstract class, Callback, with two abstract sub-classes, JobCallback and NotificationCallback, and four concrete classes: DomainJobCallback, TransferJobCallback, DomainNotificationCallback, and TransferNotificationCallback.

                                                                                 +-------------------------+                                                                                  
|  Callback (abstract)    |                                                                                  
+-------------------------+                                                                                  
/-\                                                                                             
/-   -\                                                                                           
/--       --\                                                                                        
/-             -\                                                                                      
/--                 --\                                                                                   
/-                       -\     &lt;ROOT&gt;.notify != null                                                       
&lt;ROOT&gt;.job != null    /--                           --\                                                                              
/--                                 -\                                                                            
/-                                      --\                                                                         
/--                                           -\                                                                       
/-                                                --\                                                                    
/--                                                     -\                                                                  
/-                                                          --                                                                
+------------------------+                                 +-----------------------------------+                                              
| JobCallback (abstract) |                                 | NotificationCallback (abstract)   |                                              
+------------------------+                                 +-----------------------------------+                                              
/-                                                                   /  --                                                         
/-  \-                                 &lt;ROOT&gt;.object.type == &quot;Domain&quot;/-     \-                                                       
/-      \                                                             /         \--                                                    
/-         \-                                                         /-             \--                                                 
&lt;ROOT&gt;.object.type == &quot;Domain&quot;    /-             \ &lt;ROOT&gt;.object.type == &quot;Transfer&quot;                     /-                  \-   &lt;ROOT&gt;.object.type = &quot;Transfer&quot;             
/-                \-                                                   /                      \--                                            
/-                    \                                                /-                          \--                                         
/-                       \-                                             /                               \-                                       
/-                           \                                          /-                                  \--                                    
/-                              \-                                       -                                       \-                                  
+-------------------------------+        +--------------------------------+   +--------------------------------------+        +----------------------------------------+     
|DomainJobCallback (concrete)   |        | TransferJobCallback (concrete) |   |DomainNotificationCallback (concrete) |        | TransferNotificationCallback (concrete)|     
+-------------------------------+        +--------------------------------+   +--------------------------------------+        +----------------------------------------+     

Sample JSON:

DomainJobCallback

{
  &quot;job&quot;: &quot;example-job&quot;,
  &quot;object&quot;: {
    &quot;type&quot;: &quot;Domain&quot;
  }
}

TransferJobCallback

{
  &quot;job&quot;: &quot;example-job&quot;,
  &quot;object&quot;: {
    &quot;type&quot;: &quot;Transfer&quot;
  }
}

DomainNotificationCallback

{
  &quot;notify&quot;: &quot;example-notify&quot;,
  &quot;object&quot;: {
    &quot;type&quot;: &quot;Domain&quot;
  }
}

TransferNotificationCallback

{
  &quot;notify&quot;: &quot;example-notify&quot;,
  &quot;object&quot;: {
    &quot;type&quot;: &quot;Transfer&quot;
  }
}

Approach 1:
Initially I thought of using com.fasterxml.jackson.annotation.JsonTypeInfo.Id#DEDUCTION on Callback and com.fasterxml.jackson.annotation.JsonTypeInfo.Id#NAME on JobCallback and NotificationCallback. However, I got to know that overriding @JsonTypeInfo is not possible (https://github.com/FasterXML/jackson-databind/issues/3358).

Approach 2:
Then I wrote a custom deserializer that checks the presence of the field .job and .notify and accordingly delegates the work to parser of each sub-type. I am assumingly it should be easy from here to reuse the default parsing as now I have determined the sub-type and I can look at the value of .object.type to get to the concrete type, for this I added @JsonTypeInfo and @JsonSubTypes to the subtype classes (JobCallback and NotificationCallback), and returned mapper.treeToValue(node, Callback.JobCallback.class); and mapper.treeToValue(node, Callback.NotificationCallback.class); from parseJobCallback and parseNotificationCallback.
This approach can be found commented-out.

I got the following exception:

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 &#39;object.type&#39;
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)

Approach 3:
Parse the value of .object.type after sub-type is known.

I went further with parsing and even extracted out the value of the concrete type once the sub-types were known. However, this resulted in a StackOverflowError. I am assuming this is getting into an infinite loop cause I am calling mapper.treeToValue(node, Callback.JobCallback.DomainJobCallback.class) and that too is using the same deserializer.
I know if I parse each of the fields and then construct the concrete objects, it would solve the problem. But I don't want to parse it manually to that depth.

I am also not sure if I should be initializing a object mapper within CallbackDeserializer as I am currently doing.

Here's the code to replicate this:

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 = &quot;{\n&quot; +
                &quot;  \&quot;job\&quot;: \&quot;example-job\&quot;,\n&quot; +
                &quot;  \&quot;object\&quot;: {\n&quot; +
                &quot;    \&quot;type\&quot;: \&quot;Domain\&quot;\n&quot; +
                &quot;  }\n&quot; +
                &quot;}\n&quot;;

        Callback callback = objectMapper.readValue(jsonPayload, Callback.class);

        System.out.println(&quot;callback = &quot; + callback);
    }

    public static class CallbackDeserializer extends JsonDeserializer&lt;Callback&gt; {

        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(&quot;job&quot;);
            final JsonNode notificationCallbackNode = node.get(&quot;notify&quot;);

            if (jobCallbackNode != null) {
                return parseJobCallback(node, jsonParser);
            }
            else if (notificationCallbackNode != null) {
                return parseNotificationCallback(node, jsonParser);
            }
            else {
                throw InvalidDefinitionException.from(jsonParser, &quot;Invalid callback type&quot;, (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(&quot;object&quot;).get(&quot;type&quot;).asText();

            if (type.equals(&quot;Domain&quot;)) {
                return mapper.treeToValue(node, Callback.JobCallback.DomainJobCallback.class);
            }
            else if (type.equals(&quot;Transfer&quot;)) {
                return mapper.treeToValue(node, Callback.JobCallback.TransferJobCallback.class);
            }
            throw InvalidDefinitionException.from(jsonParser, &quot;Invalid job callback type&quot;, (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(&quot;object&quot;).get(&quot;type&quot;).asText();
            if (type.equals(&quot;Domain&quot;)) {
                return mapper.treeToValue(node, Callback.NotificationCallback.DomainNotificationCallback.class);
            }
            else if (type.equals(&quot;Transfer&quot;)) {
                return mapper.treeToValue(node, Callback.NotificationCallback.TransferNotificationCallback.class);
            }
            throw InvalidDefinitionException.from(jsonParser, &quot;Invalid job callback type&quot;, (JavaType) null);
        }
    }

    @JsonDeserialize(using = CallbackDeserializer.class)
    @JsonIgnoreProperties(ignoreUnknown = true)
    public abstract static class Callback {

        private Obj object;

        //        @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = &quot;object.type&quot;)
//        @JsonSubTypes({
//                @JsonSubTypes.Type(value = JobCallback.DomainJobCallback.class, name = &quot;Domain&quot;),
//                @JsonSubTypes.Type(value = JobCallback.TransferJobCallback.class, name = &quot;Transfer&quot;),
//        })
        @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 = &quot;object.type&quot;)
//        @JsonSubTypes({
//                @JsonSubTypes.Type(value = NotificationCallback.DomainNotificationCallback.class, name = &quot;Domain&quot;),
//                @JsonSubTypes.Type(value = NotificationCallback.TransferNotificationCallback.class, name = &quot;Contact&quot;)
//        })
        @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

得分: 1

我认为你需要配置ObjectMapper以使用基于字段的序列化(它默认为基于Bean的 - 即它寻找getter/setter)。我还发现模块比注解更容易工作。例如:

final SimpleModule module = new SimpleModule();
module.addDeserializer(Callback.class, new CallbackDeserializer());
objectMapper.registerModule(module);
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

Callback callback = objectMapper.readValue(jsonPayload, Callback.class);

// 检查结果。
System.out.println("callback = " + objectMapper.writeValueAsString(callback));

如果我运行这段代码,我会得到以下输出,这表明它已成功地映射了JSON:

callback = {"object":{"type":"Domain"},"job":"example-job"}
英文:

I think you need to configure the ObjectMapper to use field-based serialization (it defaults to bean-based - i.e. it looks for getter/setters). I also find Modules easier to get working than annotations. E.g.:

    final SimpleModule module = new SimpleModule();
module.addDeserializer(Callback.class, new CallbackDeserializer());
objectMapper.registerModule(module);
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
Callback callback = objectMapper.readValue(jsonPayload, Callback.class);
// Check the results.
System.out.println(&quot;callback = &quot; + objectMapper.writeValueAsString(callback));

If I run this then I get the following, which suggests it has mapped the JSON successfully:

callback = {&quot;object&quot;:{&quot;type&quot;:&quot;Domain&quot;},&quot;job&quot;:&quot;example-job&quot;}

huangapple
  • 本文由 发表于 2023年5月7日 16:58:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定