0

Let say I have the following JSON

{
    id: 5,
    sub: {
        id: 7
    }
}

And my c# is defined as

public class outer {
    public int id;
    public inner sub;

    public class inner {
        private _outerRef;
        public inner(outer outerRef) {
            _outerRef = outerRef;
        }

        public int id;
        public string name {
            get {
                return id + "." + _outerRef.id;
            }
        }
    }
}

How can I de-serialize the JSON so that a reference to the outer class is passed along?

EDIT:

Technically, my c# class will be

public class outer {
        public int id;
        public List<inner> subs;

        public class inner {
            private _outerRef;
            public inner(outer outerRef) {
                _outerRef = outerRef;
            }

            public int id;
            public string name {
                get {
                    return id + "." + _outerRef.id;
                }
            }
        }
    }
Matt
  • 25,943
  • 66
  • 198
  • 303
  • 2
    Don't know if there is any automated method for it (I don't think so), so you seem to have 2 options: write a custom converter or a "trick" implementation: after deserializing do items.ForEach( outer => outer.inner.SetOuter(outer)); right after reading data from json. – Jarek Kożdoń Apr 21 '18 at 22:34
  • 1
    As an alternative, you could replace the `List subs` with a custom subclass of `Collection` that automatically maintains parent/child relationships. See for instance [Intercept list population to assign values in deserialization](https://stackoverflow.com/a/42725244/3744182) or [Store/retrieve child-parent relationship with JsonConverter](https://stackoverflow.com/a/46837877/3744182). – dbc Apr 21 '18 at 23:26

0 Answers0