{"record":{"id":"ddfd2c9700f3f85c","repo":"JamesNK/Newtonsoft.Json","slug":"error-setting-value-to-0-on-1","errorCode":null,"errorMessage":"Error setting value to '{0}' on '{1}'.","messagePattern":"Error setting value to '(.+?)' on '(.+?)'\\.","errorType":"exception","errorClass":"JsonSerializationException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs","lineNumber":87,"sourceCode":"                if (_setter == null)\n                {\n                    _setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(_memberInfo);\n                }\n\n#if DEBUG\n                // dynamic method doesn't check whether the type is 'legal' to set\n                // add this check for unit tests\n                if (value != null && !ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))\n                {\n                    throw new JsonSerializationException(\"Incompatible value. Cannot set {0} to type {1}.\".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));\n                }\n#endif\n\n                _setter(target, value);\n            }\n            catch (Exception ex)\n            {\n                throw new JsonSerializationException(\"Error setting value to '{0}' on '{1}'.\".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);\n            }\n        }\n\n        /// <summary>\n        /// Gets the value.\n        /// </summary>\n        /// <param name=\"target\">The target to get the value from.</param>\n        /// <returns>The value.</returns>\n        public object? GetValue(object target)\n        {\n            try\n            {\n                if (_getter == null)\n                {\n                    _getter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(_memberInfo);\n                }\n\n                return _getter(target);","sourceCodeStart":69,"sourceCodeEnd":105,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs#L69-L105","documentation":"Thrown by DynamicValueProvider.SetValue when the compiled dynamic-method setter fails while writing a value into a member (field or property) of the target object during serialization or deserialization. The '{0}' placeholder is the member name and '{1}' is the runtime type of the target. The original exception (e.g. TargetInvocationException, InvalidCastException) is preserved as the InnerException so the real cause is inspectable.","triggerScenarios":"Deserializing JSON into a property whose setter throws (e.g. a property with validation logic in the setter, a read-only auto-property with no setter, a type mismatch where the deserialized value cannot be assigned to the member type), or serializing where a getter is invoked but SetValue is used to populate during deserialization. Common during DeserializeObject<T> when the JSON contains a value incompatible with the target member type.","commonSituations":"Passing a JSON string into an int property, deserializing into a struct/record with init-only setters that the dynamic provider cannot bind, a property setter that throws ArgumentException on invalid input, value/type mismatches after a schema change, or a member that was renamed on the C# side but the JSON still carries the old name/type.","solutions":["Inspect ex.InnerException to find the real failure (cast, null-ref, setter validation) before changing anything.","Verify the JSON value type matches the target property type; add a custom JsonConverter or a property-level converter for mismatches.","If the property has no public setter, add one, use [JsonProperty] to map to a settable member, or use a constructor/[JsonConstructor] that accepts the value.","Catch JsonSerializationException around JsonConvert.DeserializeObject and log Path (ex.Path) to locate the offending JSON member."],"exampleFix":"// before: deserializing incompatible type\npublic class Model { public int Age { get; set; } }\nvar m = JsonConvert.DeserializeObject<Model>(\"{\\\"Age\\\":\\\"twenty\\\"}\");\n// after: map via string property + conversion\npublic class Model {\n    [JsonProperty(\"age\")] private string _ageRaw;\n    public int Age => int.Parse(_ageRaw);\n}","handlingStrategy":"try-catch","validationCode":"if (value == null || !targetType.GetProperty(memberName)?.PropertyType.IsAssignableFrom(value.GetType()) == true) throw new ArgumentException(\"incompatible\");","typeGuard":"// guard the value type before serialize\nstatic bool CanAssign(Type memberType, object value) => value == null ? !memberType.IsValueType || Nullable.GetUnderlyingType(memberType) != null : memberType.IsAssignableFrom(value.GetType());","tryCatchPattern":"try {\n    var obj = JsonConvert.DeserializeObject<T>(json, settings);\n} catch (JsonSerializationException ex) when (ex.Message.Contains(\"Error setting value\")) {\n    logger.Error(ex, \"Deser failed at {Path}: {Inner}\", ex.Path, ex.InnerException?.Message);\n    throw;\n}","preventionTips":["Keep property setters side-effect free and tolerant of the deserialized value type.","Use [JsonConstructor] for read-only/init-only members so the value is constructor-bound.","Register a custom JsonConverter for type-mismatched members.","Configure JsonSerializerSettings.Error to skip and log rather than abort on a single bad member."],"tags":["deserialization","serialization","reflection","dynamic-value-provider"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}