public string SerializeToString(object data, int?maxDepth = null, ICollection <string> excludedPropertyNames = null, bool ignoreSerializationErrors = false)
        {
            JsonSerializer serializer = JsonSerializer.Create(DefaultSettings);

            if (!maxDepth.HasValue)
            {
                maxDepth = Int32.MaxValue;
            }

            using (var sw = new StringWriter()) {
                using (var jw = new JsonTextWriterWithDepth(sw)) {
                    jw.Formatting = Formatting.Indented;
                    Func <JsonProperty, bool> include = p => ShouldSerialize(jw, p, maxDepth.Value, excludedPropertyNames);
                    var resolver = new ConditionalContractResolver(include);
                    serializer.ContractResolver = resolver;
                    if (ignoreSerializationErrors)
                    {
                        serializer.Error += (sender, args) => { args.ErrorContext.Handled = true; }
                    }
                    ;
                    serializer.Serialize(jw, data);
                }

                return(sw.ToString());
            }
        }
        private bool ShouldSerialize(JsonTextWriterWithDepth jw, JsonProperty property, int maxDepth, ICollection <string> excludedPropertyNames)
        {
            if (excludedPropertyNames != null && property.PropertyName.AnyWildcardMatches(excludedPropertyNames, true))
            {
                return(false);
            }

            bool serializesAsObject = !IsIntrinsicType(property.PropertyType);

            return(serializesAsObject ? jw.CurrentDepth < maxDepth : jw.CurrentDepth <= maxDepth);
        }