Skip to content

@JacksonInject with @JsonIdentityInfo causes deserialization failure (unresolved forward reference) #639

Closed

Description

@cowwoc

Jackson 2.4.4 is able to successfully deserialize forward references, but it fails to do so if the constructor contains a @JacksonInject parameter.

Activity

  1. cowwoc commented on Nov 28, 2014

    @cowwoc
    Author

    Testcase: https://gist.github.com/cowwoc/743d2839bc7297a47516

    Inlined ObjectIdWithInjectable639Test.java:


    class ObjectIdWithInjectable639Test extends DatabindTestUtil {
        // for [databind#639]
        @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
        public static final class Parent2 {
            @JsonProperty
            public Child2 child;
    
            @JsonCreator
            public Parent2(@JacksonInject("context") String context) {
            }
        }
    
        @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
        public static final class Child2 {
            @JsonProperty
            private final Parent2 parent;
    
            @JsonCreator
            public Child2(@JsonProperty("parent") Parent2 parent) {
                this.parent = parent;
            }
        }
    
        @Test
        void objectIdWithInjectable() throws Exception {
            ObjectMapper mapper = new ObjectMapper()
                    .setInjectableValues(new InjectableValues.Std().
                            addValue("context", "Stuff"));
            Parent2 parent2 = new Parent2("foo");
            Child2 child2 = new Child2(parent2);
            parent2.child = child2;
    
            String json2 = mapper.writeValueAsString(parent2);
            parent2 = mapper.readValue(json2, Parent2.class);
            assertNotNull(parent2);
            assertNotNull(parent2.child);
        }
    }
    
  2. changed the title [-]Support mixing forward references with @JacksonInject[/-] [+]@JsonInject causes deserialization failure (unresolved forward reference)[/+] on Dec 19, 2014
  3. cowtowncoder commented on Jun 15, 2016

    @cowtowncoder
    Member

    Actually I think this is different, and bit trickier. Problem is that there is an actual cycle from deserializer perspective, since parent2 may not be constructed before all JSON for it (and its descendants) are consumed; but its child child2 needs parent reference passed via constructor. So the solution here would be to remove @JsonCreator on child2 with non-creator alternative.

    Except that in theory, since parent2 only needs injectable value, perhaps implementing #1268 would allow this to be handled even without removing of @JsonCreator.

  4. cowtowncoder commented on Jul 19, 2016

    @cowtowncoder
    Member

    So, the json output here is something like:

    {"@id":1,"child":{"@id":2,"parent":1}}

    and the reason this can not be resolved at this point is only partially due to @JacksonInject. The underlying problem is that neither Parent2 nor Child2 may be constructed before all data is available, as both have @JsonCreator annotated constructor.
    Now, in theory Jackson could notice that the only parameter for Parent2 is injectable and create it immediately -- however, before #1381 is implemented, there is no way to indicate that something is purely injectable, that is, something that only comes via injection and not data. With #1268 it should be possible to define this, and with that, this problem would be solvable theoretically.

  5. added a commit that references this issue on Jul 19, 2016
  6. changed the title [-]@JsonInject causes deserialization failure (unresolved forward reference)[/-] [+]`@JacksonInject` causes deserialization failure (unresolved forward reference)[/+] on Mar 30, 2017
  7. added
    has-failing-test
    and removed on Oct 27, 2020
  8. added a commit that references this issue on Sep 19, 2024
  9. cowtowncoder commented on Nov 26, 2025

    @cowtowncoder
    Member

    Summary of investigation by Claude:


    Issue #639: @JacksonInject with @JsonIdentityInfo Forward References - Analysis

    Issue Summary

    Issue: #639 - @JacksonInject with Forward References
    Status: Open since November 2014
    Test Case: ObjectIdWithInjectable639Test.java (marked with @JacksonTestFailureExpected)

    Jackson fails to deserialize forward references when a constructor parameter includes @JacksonInject, though the same forward references work fine without injection.

    Test Case

    @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
    public static final class Parent2 {
        @JsonProperty
        public Child2 child;
    
        @JsonCreator
        public Parent2(@JacksonInject("context") String context) {
        }
    }
    
    @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
    public static final class Child2 {
        @JsonProperty
        private final Parent2 parent;
    
        @JsonCreator
        public Child2(@JsonProperty("parent") Parent2 parent) {
            this.parent = parent;
        }
    }

    JSON: {"@id":1,"child":{"@id":2,"parent":1}}

    Expected: Both objects deserialize with proper circular reference resolution.
    Actual: MismatchedInputException: Cannot resolve ObjectId forward reference using property 'child' (of type Parent2): Bean not yet resolved

    Root Cause Analysis

    Deserialization Flow

    1. Start deserializing Parent2 (will be id:1)

      • Parent2 uses property-based creator with @JacksonInject parameter
      • Bean cannot be fully constructed until all parameters are available
    2. Deserialize child property → Start Child2 (will be id:2)

      • Child2 constructor needs parent parameter = forward reference to id:1 (Parent2)
      • Since Parent2 (id:1) hasn't been bound yet, throws UnresolvedForwardReference
    3. Create BeanReferring for the child property

      • Located at: BeanDeserializer._deserializeUsingPropertyBased() line 496-506
      • The exception is caught and a BeanReferring is created
      • This is registered with the forward reference's ReadableObjectId
    4. Complete Parent2 construction

      • PropertyBasedCreator.build() calls _valueInstantiator.createFromObjectWith()
      • Then calls buffer.handleIdValue(ctxt, bean) which calls roid.bindItem(bean)
      • bindItem() immediately calls handleResolvedForwardReference() on all referrings
      • Problem: BeanReferring._bean is still null at this point!
    5. Set bean on referrings (BeanDeserializer.java line 568-572)

      • After creator.build() returns
      • Calls referring.setBean(bean) on all BeanReferring objects
      • Too late: Forward references were already attempted to be resolved in step 4

    The Timing Issue

    Current Flow:
    1. creator.build(ctxt, buffer)
       ├─> createFromObjectWith() - creates bean
       └─> handleIdValue()
           └─> bindItem(bean)
               └─> handleResolvedForwardReference() ← _bean is NULL, throws error!
    
    2. referring.setBean(bean) ← happens AFTER bindItem()
    

    The issue is that bindItem() is called inside creator.build(), but setBean() is called after creator.build() returns.

    Why Injectables Cause This

    Without @JacksonInject:

    • Beans can be constructed immediately with all parameters from JSON
    • setBean() would be called before the bean is bound
    • Forward references resolve correctly

    With @JacksonInject:

    • Bean construction is delayed until PropertyValueBuffer.getParameters() handles injection
    • The bean is created and bound before BeanReferring.setBean() is called
    • Forward references fail because _bean is still null

    Related Code Locations

    Key Classes

    BeanDeserializer.java:

    • Line 496-507: Catches UnresolvedForwardReference and creates BeanReferring
    • Line 551: creator.build() creates bean and binds ObjectId
    • Line 568-572: Sets bean on all BeanReferring objects (too late!)
    • Line 1212-1240: BeanReferring inner class

    PropertyBasedCreator.java:

    • Line 277-292: build() method
      • Line 279: Creates bean via createFromObjectWith()
      • Line 284: Calls handleIdValue() which binds the ObjectId

    PropertyValueBuffer.java:

    • Line 380-403: handleIdValue() method
      • Line 385: Calls roid.bindItem(bean) which triggers forward reference resolution

    ReadableObjectId.java:

    • Line 56-68: bindItem() method
      • Line 65: Calls handleResolvedForwardReference() on all referrings

    Attempted Fix

    Approach

    Modify BeanReferring to defer property assignment when bean isn't available yet:

    1. Add _resolvedValue field to store the resolved value
    2. In handleResolvedForwardReference(): if _bean is null, store value in _resolvedValue
    3. In setBean(): if _resolvedValue is set, apply it to the bean

    Implementation

    File: src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializer.java

    static class BeanReferring extends Referring
    {
        private final DeserializationContext _context;
        private final SettableBeanProperty _prop;
        private Object _bean;
    
        // NEW: Store resolved value for later application
        private Object _resolvedValue;
    
        public void setBean(Object bean) throws IOException {
            _bean = bean;
            // Apply deferred resolution if value was resolved before bean was available
            if (_resolvedValue != null) {
                // Type check to handle complex nested reference scenarios
                if (_prop.getType().getRawClass().isAssignableFrom(_resolvedValue.getClass())) {
                    _prop.set(_bean, _resolvedValue);
                } else {
                    _resolvedValue = null;
                }
            }
        }
    
        @Override
        public void handleResolvedForwardReference(Object id, Object value) throws IOException
        {
            if (_bean == null) {
                // Defer: bean not yet available (likely due to injectable constructor params)
                _resolvedValue = value;
            } else {
                // Apply immediately: bean is ready
                _prop.set(_bean, value);
            }
        }
    }

    Issues Discovered

    The fix revealed a deeper architectural problem: In complex nested scenarios with forward references in constructor parameters, the wrong BeanReferring receives resolution callbacks.

    Observed behavior:

    • JSON: {"@id":1,"child":{"@id":2,"parent":1}}
    • The BeanReferring for Parent2's child property receives Parent2 (id:1) as the resolved value
    • Expected: It should receive Child2 (id:2)
    • The type mismatch check prevents the error, but child remains null

    Why this happens:

    1. Child2's constructor needs parent = forward ref to Parent2 (id:1)
    2. This causes Child2 deserialization to throw UnresolvedForwardReference
    3. The exception is caught at the child property level
    4. A BeanReferring is created for the child property
    5. This BeanReferring is registered with Parent2's ReadableObjectId (id:1)
    6. When Parent2 is bound, it notifies ALL referrings registered with id:1
    7. This includes the child property's BeanReferring, which receives Parent2 as the value

    The architecture conflates two different concerns:

    • Constructor parameter forward reference: Child2.parent waiting for Parent2 (id:1)
    • Property forward reference: Parent2.child waiting for Child2 (id:2)

    Currently, both get registered with the same ReadableObjectId, causing incorrect resolution callbacks.

    Comparison with Working Test

    Test #538 (ObjectIdWithInjectables538Test) - Works correctly:

    • Both classes have @JacksonInject in constructors
    • BUT: The circular references are in regular fields, not constructor parameters
    • Forward references can be resolved after objects are constructed
    • No timing issue with injectable parameters

    Key difference: Constructor parameter forward references require the bean to exist before the forward reference can be resolved, creating a circular dependency that the current architecture doesn't handle when combined with injectable parameters.

    Recommendations

    Short-term Workaround

    Users encountering this issue can work around it by:

    1. Moving forward-referenced properties from constructor parameters to regular fields
    2. Using a default constructor with @JacksonInject parameters
    3. Setting circular references via regular setters after construction

    Long-term Solution Options

    Option 1: Separate Referring Types

    Create a distinct CreatorPropertyReferring class for constructor parameter forward references that:

    • Stores the parameter value in PropertyValueBuffer rather than trying to set it immediately
    • Allows the bean to be constructed with the forward reference value
    • Properly distinguishes parameter-level from property-level forward references

    Option 2: Delayed ObjectId Binding

    Delay the bindItem() call until after all referrings have had setBean() called:

    • Modify PropertyBasedCreator.build() to NOT call handleIdValue() immediately
    • Return the bean and let the caller bind the ObjectId after setting up referrings
    • Requires significant refactoring of the creator/buffer flow

    Option 3: Two-Phase Resolution

    Implement two-phase forward reference resolution:

    • Phase 1: Collect all forward references without resolving
    • Phase 2: After all beans are constructed, resolve forward references
    • Most invasive but most robust solution

    Testing Recommendations

    Before implementing a fix:

    1. Create additional test cases isolating different scenarios:
    2. Test with deeper nesting (3+ levels of circular references)
    3. Test with multiple forward references in single constructor

    Conclusion

    Issue #639 exposes a fundamental limitation in how Jackson handles the combination of:

    • Property-based creators (constructors/factory methods)
    • Injectable constructor parameters
    • Forward references in those same constructor parameters

    The current architecture's timing of ObjectId binding (inside creator.build()) conflicts with the timing of BeanReferring initialization (after creator.build()). The attempted fix reveals that the problem is deeper than just timing - the forward reference registration mechanism doesn't properly distinguish between constructor parameter dependencies and property dependencies.

    A proper fix will require careful architectural changes to one of the core deserialization flows, with thorough testing to ensure existing functionality isn't broken.


    Analysis Date: 2025-11-25
    Jackson Version: 2.21.0-SNAPSHOT (2.x branch)
    Analyst: Claude (Anthropic)

  10. added a commit that references this issue on Mar 11, 2026
  11. changed the title [-]`@JacksonInject` causes deserialization failure (unresolved forward reference)[/-] [+]`@JacksonInject` with `@JsonIdentityInfo` causes deserialization failure (unresolved forward reference)[/+] on Mar 11, 2026
  12. self-assigned this
    on Mar 11, 2026
  13. added this to the 3.2.0 milestone on Mar 11, 2026
  14. added a commit that references this issue on Mar 11, 2026
  15. cowtowncoder commented on Mar 11, 2026

    @cowtowncoder
    Member

    2nd time's the charm; Claude crunched an acceptable fix, to be included in 3.2.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

3.2has-failing-testobjectid

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions