{"record":{"id":"d21fc7cdab58a836","repo":"JamesNK/Newtonsoft.Json","slug":"unable-to-serialize-instance-of-0","errorCode":null,"errorMessage":"Unable to serialize instance of '{0}'.","messagePattern":"Unable to serialize instance of '(.+?)'\\.","errorType":"exception","errorClass":"JsonSerializationException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs","lineNumber":442,"sourceCode":"            MemberInfo? extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType);\n            if (extensionDataMember != null)\n            {\n                SetExtensionDataDelegates(contract, extensionDataMember);\n            }\n\n            // serializing DirectoryInfo without ISerializable will stackoverflow\n            // https://github.com/JamesNK/Newtonsoft.Json/issues/1541\n            if (Array.IndexOf(BlacklistedTypeNames, objectType.FullName) != -1)\n            {\n                contract.OnSerializingCallbacks.Add(ThrowUnableToSerializeError);\n            }\n\n            return contract;\n        }\n\n        private static void ThrowUnableToSerializeError(object o, StreamingContext context)\n        {\n            throw new JsonSerializationException(\"Unable to serialize instance of '{0}'.\".FormatWith(CultureInfo.InvariantCulture, o.GetType()));\n        }\n\n        private MemberInfo? GetExtensionDataMemberForType(Type type)\n        {\n            IEnumerable<MemberInfo> members = GetClassHierarchyForType(type).SelectMany(baseType =>\n            {\n                IList<MemberInfo> m = new List<MemberInfo>();\n                m.AddRange(baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));\n                m.AddRange(baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));\n\n                return m;\n            });\n\n            MemberInfo? extensionDataMember = members.LastOrDefault(m =>\n            {\n                MemberTypes memberType = m.MemberType();\n                if (memberType != MemberTypes.Property && memberType != MemberTypes.Field)\n                {","sourceCodeStart":424,"sourceCodeEnd":460,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L424-L460","documentation":"Thrown at serialization time for types whose FullName is in Json.NET's BlacklistedTypeNames (e.g. System.IO.DirectoryInfo, System.IO.FileInfo). For these types the contract resolver registers an OnSerializing callback (ThrowUnableToSerializeError, line 440) that throws a JsonSerializationException before serialization proceeds. This guard exists because serializing such types without ISerializable support causes a stack overflow (GitHub issue #1541).","triggerScenarios":"JsonConvert.SerializeObject(new DirectoryInfo(...)) or any other blacklisted System type instance. The error fires on the OnSerializing hook the moment serialization begins.","commonSituations":"Attempting to JSON-serialize filesystem objects, process objects, or other System types that hold unmanaged/native state. Also hit when a DTO transitively contains a DirectoryInfo/FileInfo member that gets pulled into the graph.","solutions":["Do not serialize the blacklisted type; project its relevant fields into a plain DTO and serialize that instead.","Add [JsonIgnore] to the DirectoryInfo/FileInfo member so it is excluded from the graph.","Write a custom JsonConverter for the type that emits only the fields you need (e.g. FullName)."],"exampleFix":"// before\nvar json = JsonConvert.SerializeObject(directoryInfo); // throws Unable to serialize\n\n// after\nvar dto = new { directoryInfo.FullName, directoryInfo.Name };\nvar json = JsonConvert.SerializeObject(dto);","handlingStrategy":"validation","validationCode":"static readonly HashSet<string> Blacklist = new() { \"System.IO.DirectoryInfo\", \"System.IO.FileInfo\" };\nif (value != null && Blacklist.Contains(value.GetType().FullName))\n    throw new InvalidOperationException($\"Do not serialize {value.GetType()}; project to a DTO.\");\nvar json = JsonConvert.SerializeObject(value);","typeGuard":"static bool IsBlacklisted(object? value) =>\n    value is System.IO.DirectoryInfo || value is System.IO.FileInfo;","tryCatchPattern":"try { json = JsonConvert.SerializeObject(value); }\ncatch (JsonSerializationException ex) when (ex.Message.StartsWith(\"Unable to serialize instance\"))\n{\n    // project the object into a DTO and retry\n}","preventionTips":["Never serialize filesystem/process objects directly; map them to plain DTOs.","Add [JsonIgnore] to members that hold DirectoryInfo/FileInfo.","Audit DTO graphs for blacklisted System types before serializing."],"tags":["serialization","blacklisted-type","stack-overflow-guard","filesystem"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}