I am trying to serialize a complex object through DataContract . The object has a list of sub-objects, which in turn have their own list (let's call it - tree leaves). These leaves, for example, the first item in the list of the main object, can be reached from other list items (the link is the same). It turns out quite a complicated graph, in which there are many links.

When deserializing, each element of the list has its own leaves, i.e. links are lost, if in the source object it is the same sheet, then after deserialization it is just a copy.

Like that

  AA / \ / \ BC ====> BC \ / | | DDD[копия] 

(this is a very simplified diagram)

I tried for all classes to register DataContract(IsReference = true) , so, just in case, it did not help.

Is there a more “quick” way to correctly deserialize, except as a “manual” alignment of the structure of the repeating source object?

Thank.

  • one
    When creating a DataContractSerializer set the settings for its new DataContractSerializerSettings { PreserveObjectReferences = true } . - Alexander Petrov
  • one
    Or you can use the NetDataContractSerializer . - Alexander Petrov
  • @AndreyNOP, oh, I was wrong in my nicknames. - A1essandro
  • @AlexanderPetrov, please issue a response. Your decision helped. - A1essandro

1 answer 1

When creating a serializer, set the PreserveObjectReferences = true setting to it.

 var settings = new DataContractSerializerSettings { PreserveObjectReferences = true }; var dcs = new DataContractSerializer(typeof(SomeType), settings); 

You can also use the NetDataContractSerializer .