Mike Bruno
Mike Bruno

Reputation: 634

How do I handle erroneously-detected reference loops with JsonConvert.SerializeObject() when JsonCoverters need to be passed?

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?

Upvotes: 2

Views: 301

Answers (2)

Mike Bruno
Mike Bruno

Reputation: 634

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.

Upvotes: 0

SBFrancies
SBFrancies

Reputation: 4240

JsonSerializerSettings has a property which is a list of converters:

JsonConvert.SerializeObject(envelope, Formatting.Indented, new 
        JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            Converters = new List<JsonConverter> { },
        });

Upvotes: 1

Related Questions