2

We have a need to serialize objects with versioning, so we are encapsulating them in an envelope:

protected void OnStateChanged(Object state) 
{
    var envelope = new WorkerStateData<Object> 
    {
        StateVersion = workerConfig.CurrentStateVersion,
        Value = state
    };
    String serializedState = JsonConvert.SerializeObject(envelope, new VersionConverter());
}

With one of our entities that need to be serialized, Newtonsoft is detecting a reference loop. I've confirmed that no such loop exists by forcing serialization ReferenceLoopHandling.Serialize:

var serializeSettings = new JsonSerializerSettings();
serializeSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
String serialized = JsonConvert.SerializeObject(state, Formatting.Indented, serializeSettings);

This test serialization succeeds with no reference loop.

The problem is that there doesn't seem to be an overload of JsonConvert.SerializeObject which accepts both JsonSerializerSettings and JsonConverter[]. Without having both of those pieces of functionality, I can't integrate this fix into our main code base.

Can anyone suggest another way to bypass the reference loop check?

Mike Bruno
  • 600
  • 2
  • 9
  • 26
  • Is this just a duplicate of [Is there any way to add JsonSerializerSettings to a custom JsonConverter](https://stackoverflow.com/q/51429420/3744182), or do you need some help with the erroneous `ReferenceLoopHandling` error? – dbc Dec 16 '21 at 04:36
  • My dev lead wanted to avoid using custom serialization settings. I was hoping to find out why Json.Net was detecting a reference loop. It turns out it is because we are overriding the Equals() method in one of our classes. – Mike Bruno Dec 17 '21 at 15:00

2 Answers2

1

JsonSerializerSettings has a property which is a list of converters:

JsonConvert.SerializeObject(envelope, Formatting.Indented, new 
        JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            Converters = new List<JsonConverter> { },
        });
SBFrancies
  • 3,987
  • 2
  • 14
  • 37
0

Please see this github issue that I submitted to the Json.Net team. The problem we experienced was due to us overriding the default Equals() method in one of our classes.

While there really isn't a reference loop, updating Json.Net to handle such situations might break backwards compatibility. Long story short, guidance from Json.Net is to use custom Serializer settings as proposed in the accepted answer to this question.

Mike Bruno
  • 600
  • 2
  • 9
  • 26
  • See [Why doesn't reference loop detection use reference equality?](https://stackoverflow.com/a/46938352/3744182). You can use `JsonSerializerSettings.EqualityComparer` to override Json.NET's behavior. – dbc Dec 17 '21 at 15:09
  • My dev lead wanted to use only default serialization settings, so we had to deal with the problem. – Mike Bruno Dec 23 '21 at 16:01