From bcf910649a8976e59f5f42be12c3e712fa5e2431 Mon Sep 17 00:00:00 2001 From: Jorgen Date: Mon, 31 Aug 2015 15:34:38 +0200 Subject: [PATCH] Fixes issue Conditional deserialize #196 --- .../Serialization/JsonProperty.cs | 5 +++++ .../JsonSerializerInternalReader.cs | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/Src/Newtonsoft.Json/Serialization/JsonProperty.cs b/Src/Newtonsoft.Json/Serialization/JsonProperty.cs index 45c5e38d..daec3e00 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonProperty.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonProperty.cs @@ -235,6 +235,11 @@ namespace Newtonsoft.Json.Serialization /// /// A predicate used to determine whether the property should be serialize. public Predicate ShouldSerialize { get; set; } + /// + /// Gets or sets a predicate used to determine whether the property should be de-serialized. + /// + /// A predicate used to determine whether the property should be de-serialized. + public Predicate ShouldDeSerialize { get; set; } /// /// Gets or sets a predicate used to determine whether the property should be serialized. diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 76578a47..14f7edd8 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -2005,6 +2005,15 @@ namespace Newtonsoft.Json.Serialization continue; } + if (!ShouldDeSerialize(reader, property, newObject)) + { + if (!reader.Read()) + break; + + SetExtensionData(contract, member, reader, memberName, newObject); + continue; + } + if (property.PropertyContract == null) property.PropertyContract = GetContractSafe(property.PropertyType); @@ -2050,7 +2059,19 @@ namespace Newtonsoft.Json.Serialization OnDeserialized(reader, contract, newObject); return newObject; } + //reader, contract, member, id + private bool ShouldDeSerialize(JsonReader reader, JsonProperty property, object target) + { + if (property.ShouldDeSerialize == null) + return true; + bool shouldDeSerialize = property.ShouldDeSerialize(target); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, reader.Path, "ShouldDeSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldDeSerialize)), null); + + return shouldDeSerialize; + } private bool CheckPropertyName(JsonReader reader, string memberName) { if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.ReadAhead)