Jackson JSON gives exception on collection of nested class

前端 未结 1 1886
忘了有多久
忘了有多久 2021-01-04 05:53

Jackson JSON has no problem serializing/deserializing this class:

public class MyClass {
   public class Nested {
      public String string;
      public Ne         


        
相关标签:
1条回答
  • 2021-01-04 06:19

    Looks like the recognition of non-static inner classes is done where they are properties directly on their containing bean (BeanDeserializerBase.java line 476 in 2.6.3). So an intervening Collection deserializer would go past that. A custom deserializer is likely the simplest option here.

    Note that you can still use Jackson to read the properties of Nested, and just implement the construction of it yourself, in a custom deserializer only used when deserializing a list of Nested objects.

    To do this, annotate the list like so:

        @JsonDeserialize(contentUsing = NestedDeserializer.class)
        public List<Nested> nestedList;
    

    and then use a custom deserializer that will:

    1. Look at the parsing context when called to find the containing MyClass instance.

    2. Encapsulate a default/root-level deserializer of Nested to delegate the work of deserializing the content to.

    For example:

    public static final class NestedDeserializer extends StdDeserializer<MyClass.Nested>
        implements ResolvableDeserializer {
      private JsonDeserializer<Object> underlyingDeserializer;
    
      public NestedDeserializer() {
        super(MyClass.Nested.class);
      }
    
      @Override
      public void resolve(DeserializationContext ctxt) throws JsonMappingException {
        underlyingDeserializer = ctxt
            .findRootValueDeserializer(ctxt.getTypeFactory().constructType(MyClass.Nested.class));
      }
    
      @Override
      public Nested deserialize(JsonParser p, DeserializationContext ctxt)
          throws IOException, JsonProcessingException {
        JsonStreamContext ourContext = p.getParsingContext();
        JsonStreamContext listContext = ourContext.getParent();
        JsonStreamContext containerContext = listContext.getParent();
        MyClass container = (MyClass) containerContext.getCurrentValue();
        MyClass.Nested value = container.new Nested();
        // note use of three-argument deserialize method to specify instance to populate
        underlyingDeserializer.deserialize(p, ctxt, value);
        return value;
      }
    }
    
    0 讨论(0)
提交回复
热议问题