Json and Circular Reference Exception

前端 未结 9 1600
挽巷
挽巷 2020-11-27 03:17

I have an object which has a circular reference to another object. Given the relationship between these objects this is the right design.

To Illustrate

9条回答
  •  孤城傲影
    2020-11-27 03:48

    You need to decide which is the "root" object. Say the machine is the root, then the customer is a sub-object of machine. When you serialise machine, it will serialise the customer as a sub-object in the JSON, and when the customer is serialised, it will NOT serialise it's back-reference to the machine. When your code deserialises the machine, it will deserialise the machine's customer sub-object and reinstate the back-reference from the customer to the machine.

    Most serialisation libraries provide some kind of hook to modify how deserialisation is performed for each class. You'd need to use that hook to modify deserialisation for the machine class to reinstate the backreference in the machine's customer. Exactly what that hook is depends on the JSON library you are using.

提交回复
热议问题