question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Feature Request: Obey MaxDepth in SerializeObject()

See original GitHub issue

It would be helpful if MaxDepth worked on SerializeObject() as well, not just Deserialize().

Currently, you can use MaxDepth to stop the serializer from deserializing anything past a given depth on the initial object(s). But, you can’t currently tell it to only serialize down to a certain depth.

Additionally, it appears that the normal behavior of MaxDepth is to throw an exception, which is not desirable. It would help if there was a way to tell it to simply serialize/deserialize down to MaxDepth and stop. An exception is undesirable behavior in many circumstances.

A good example of where this is useful is on an Entity Framework database with LazyLoading enabled and virtual properties throughout. SerializeObject(user, new JsonSerializerSettings { MaxDepth = 0 }); would be useful for containing JSON serialization to just the user and their FK Ids. Without MaxDepth, JsonConvert is going to dutifully serialize most or all of the entire database.

I’m happy to write this feature if people are interested in it.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:24
  • Comments:7

github_iconTop GitHub Comments

4reactions
PaulDMendozacommented, Oct 21, 2021

How is this not fixed? Everyone who has set this expects a certain behavior and isn’t getting it.

3reactions
Mike-Logitcommented, May 3, 2022

did you find any work around for this issue.

Yes but it’s not pretty. I had to create my own JsonConverter and pass it to JsonConvert.SerializeObject.

For my use case, I wanted to log the contents of an object that contained data for executing a command or query, which I called the “Request” object:

var rawRequest = JsonConvert.SerializeObject(request, Formatting.None, new RequestJsonConverter(2));

And this is my RequestJsonConverter class:

private class RequestJsonConverter : JsonConverter
{
    private readonly int _depth;

    public RequestJsonConverter(int depth)
    {
        _depth = depth;
    }

    public override bool CanRead => false;

    public override bool CanConvert(Type objectType) => true;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var jObject = new JObject();
        var requestProperties = value.GetType().GetProperties();
        RequestJsonConverter nextConverter = null;

        foreach (var prop in requestProperties)
        {
            if (_depth <= 0)
            {
                continue;
            }

            try
            {
                var propValue = prop.GetValue(value);
                if (!prop.PropertyType.IsPrimitive &&
                    !prop.PropertyType.IsValueType &&
                    prop.PropertyType != typeof(string))
                {
                    if (propValue is null || _depth <= 1)
                    {
                        continue;
                    }

                    nextConverter ??= new RequestJsonConverter(_depth - 1);
                    var serializedPropValue = JsonConvert.SerializeObject(propValue, Formatting.None, nextConverter);
                    jObject.Add(prop.Name, serializedPropValue);
                }
                else
                {
                    jObject.Add(prop.Name, propValue.ToSafeString());
                }
            }
            catch
            {
                // ignored - property getter might have thrown an exception so skip it.
            }
        }

        jObject.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        => throw new NotImplementedException("Unsupported");
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

JsonSerializerOptions.MaxDepth Property
Gets or sets the maximum depth allowed when serializing or deserializing JSON, with the default value of 0 indicating a maximum depth of...
Read more >
Json.NET limit MaxDepth when serializing
I thought I'd limit how deep Json.NET was allowed to go to serialize data (at least then we'd get a sensible exception when...
Read more >
Untitled
Json method Feature Request: Obey MaxDepth in SerializeObject() #2191 - GitHub String Fields in Serializers – Django REST Framework Žiniatinklis2013 m. rugs ...
Read more >
MaxDepth setting
This sample uses the P:Newtonsoft.Json.JsonSerializerSettings.MaxDepth setting to constrain JSON to a maximum depth when deserializing.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found