0

I am serializing objects (similar to EF entities) or a list of objects that have references to other objects. The references of the objects get serialized, but their references won't be serialized, instead I write an int ID. The problem is that writer.CurrentDepth starts from 1 at the first Write if we are serializing a list, and starts from 0 if we are serializing an object. So at list I should stop serializing at depth 2, and at objects at depth 1, but I don't know if I am serializing a list or an object because besides writer.CurrentDepth I don't know anything else about the state of the serialization, of where we are in the process. How to find out if we are serializing an object or an array in deeper depths? I can get this info at the first call to Write, but how to get this info at the next Write calls?

I could use a static variable or a scoped service to store if we are serializing an object or an array, but this looks very ugly.

kovacs lorand
  • 741
  • 7
  • 23
  • 1
    `System.Text.Json` is a contract-based serializer. It creates a contract for each type to be serialized, the serializes according to the contract. You, however, want a different contract to apply given the location of objects in the serialization graph, which it isn't really designed for. But can you share a [mcve]? There might be workarounds using custom converters simpler than manually serializing everything. – dbc May 12 '21 at 14:20
  • @dbc I am serializing devexpress xpo objects, so I have to use custom converters. – kovacs lorand May 12 '21 at 14:29
  • 1
    Well, can you share a [mcve]? Are you making nested calls to the serializer? You can add and remove converters from the list of converters as you descend the serialization graph, maybe that would work for you. – dbc May 12 '21 at 14:36
  • @dbc Yes, I am making nested calls to the serializer. I am using one converter that can handle all my custom devexpress xpo objects, I can't change this part. What I need is to be able to pass data between nested calls to the serializer. For nested calls to be able to communicate with each other, because right now they are like in separate universes. – kovacs lorand May 12 '21 at 14:51
  • Then, rather than one converter, you could have two converters. An outer converter that serializes the full object, and an inner converter that serializes the abbreviated object. When making a nested serialization call, swap the outer converter for the inner converter by cloning the options and replacing the converter in the list of converters... – dbc May 12 '21 at 15:01
  • ... See e.g. `JsonSerializerExtensions.CopyAndRemoveConverter(this JsonSerializerOptions options, Type converterType)` from [this answer](https://stackoverflow.com/a/65430421/3744182) to [How to use default serialization in a custom System.Text.Json JsonConverter?](https://stackoverflow.com/q/65430420/3744182). – dbc May 12 '21 at 15:01

0 Answers0