How to set value of certain property on deserialization? - c#

I have a class with properties that setters depend on VeryImportantProperty. But the property shouldn't be serialized by design.
So, when I receive JSON, I have to set VeryImportantProperty during deserialization and before setting other properties.
I suppose it could be done by modifying ContractResolver. I store value for VeryImportantProperty there, but I don't know how to assign it
I tried to use following ContractResolver, but it does not affect
public class MyContractResolver : DefaultContractResolver
{
public VeryImportantClass VeryImportantPropertyValue { get; set; }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName == "VeryImportantProperty" && VeryImportantPropertyValue != null)
{
property.DefaultValue = VeryImportantPropertyValue;
property.DefaultValueHandling = DefaultValueHandling.Populate;
property.Order = -1;
}
return property;
}
}

I solved the problem by creating ContractResolver that overrides CreateContract to set Converter to custom one that overrides Create to pass my VeryImportantProperty to constructor
Code:
public class MyContractResolver : DefaultContractResolver
{
public VeryImportantClass VeryImportantPropertyValue { get; set; }
protected override JsonContract CreateContract(Type objectType)
{
var contract = base.CreateContract(objectType);
if (VeryImportantPropertyValue == null)
return contract;
// Solution for multiple classes is commented
if (objectType == typeof(ContainerClass)/* || objectType.IsSubclassOf(typeof(BaseContainer))*/)
{
contract.Converter = new ImportantClassConverter(VeryImportantPropertyValue);
}
return contract;
}
private class ImportantClassConverter: CustomCreationConverter<VeryImportantClass>
{
public EntityConverter(VeryImportantClass veryImportantPropertyValue)
{
_veryImportantPropertyValue= veryImportantPropertyValue;
}
private readonly VeryImportantClass _veryImportantPropertyValue;
public override VeryImportantClass Create(Type objectType)
{
// Might be simplified but it was used for multiple container classes with one parent
return objectType.GetConstructor(new[] { typeof(ContainerClass) })
?.Invoke(new[] { _veryImportantPropertyValue }) as ContainerClass;
}
}
}

Related

Using Newtonsoft Json how cast an int value to string

I'm just starting to check how to serialize and deserialize using json for a project where I need to use ArangoDB.
At the moment, I have a test class AnoherTestPerson:
public class AnotherTestPerson
{
public AnotherTestPerson(int id, string fullname, int age)
{
this.Id = id;
this.Fullname = fullname;
this.Age = age;
}
public int Id { get; set; }
public string Fullname { get; set; }
public int Age { get; set; }
}
Now, I need to cast the Id value to a string, because ArangoDB doesn't work when you pass a numerical value as the _key, so I'm guessing I have to do that from the serializer that the Arango driver uses, because in the project I'm going to work on, we won't have access to the classes of the entities we want to store on the data base.
Any help would be appreciated, as I'm still learning how serialization works with Json and C#.
Here's the rest of the code:
public static async Task Main(string[] args)
{
string connectionString = "private";
var arango = new ArangoContext(cs:connectionString, settings:
new ArangoConfiguration
{
Serializer = new ArangoNewtonsoftSerializer(CustomDataContractResolver.Instance)
//Using custom contract resolver for automatically changing the Id name
//from the object class to _key in the Json file
}
);
await arango.Document.CreateAsync("TestDB", typeof(AnotherTestPerson).Name, testPerson);
}
Here's the custom contract resolver. I tried changing the type of the property here but it didn't work.
public class CustomDataContractResolver : DefaultContractResolver
{
public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
property.PropertyName = "_key";
if(property.PropertyType == Type.GetType("System.Int32"))
{
property.PropertyType = Type.GetType("System.String");
}
}
return property;
}
}
EDIT
So checking the comment by SBFrancies, I implemented a basic JsonConverter:
public class ToStringJsonConverted : Newtonsoft.Json.JsonConverter
{
public static readonly ToStringJsonConverted Instance = new ToStringJsonConverted();
public override bool CanConvert(Type objectType)
{
return true;
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
and linked it to the custom ContractResolver:
public class CustomDataContractResolver : DefaultContractResolver
{
public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
property.PropertyName = "_key";
if(property.PropertyType == Type.GetType("System.Int32"))
{
property.Converter = ToStringJsonConverted.Instance;
}
}
return property;
}
}
It get's serialized as I wanted to, but the deserializing it's not working right now. I'll check how to read Json files and parse them for now.
I got the serializing and deserializing working, with help from #SBFrancies reference in the comments.
ContractResolver:
public class CustomDataContractResolver : DefaultContractResolver
{
public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
property.PropertyName = "_key";
if(property.PropertyType == Type.GetType("System.Int32"))
{
property.Converter = ToStringJsonConverted.Instance;
}
}
return property;
}
}
JsonConverter:
public class ToStringJsonConverted : Newtonsoft.Json.JsonConverter
{
public static readonly ToStringJsonConverted Instance = new ToStringJsonConverted();
public override bool CanConvert(Type objectType)
{
return true;
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
return Int32.Parse((string)reader.Value);
}
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}

Using property attributes to define which JsonConverter to use

I have a need to specify a JsonConverter for properties which are decorated with a specific attribute, in this case [DataType(DataType.PostalCode)].
I already have a custom JsonConverter for which I have set the CanConvert method as follows:
public override bool CanConvert(Type objectType) => objectType == typeof(string);
How can I make sure the PostcodeJsonConverter is used instead when the API encounters a PostalCode property?
[DataType(DataType.PostalCode)]
public string Postcode { get; set; }
I've tried the following but I suspect the DataType attribute is not available at this point.
public override bool CanConvert(Type objectType) =>
objectType == typeof(string) &&
objectType.GetCustomAttributes(true)
.OfType<DataTypeAttribute>()
.Any(dta => dta.DataType == DataType.PostalCode);
Do I need to decorate my model as follows instead?
[DataType(DataType.PostalCode)]
[JsonConverter(typeof(PostcodeJsonConverter))]
public string Postcode { get; set; }
You can make a custom ContractResolver that looks for your DataType attribute on each property and maps the values to the appropriate converter. Here is the code you would need:
public class DataTypeResolver : DefaultContractResolver
{
private Dictionary<DataType, JsonConverter> ConvertersByDataType { get; set; }
public DataTypeResolver()
{
// Adjust this list to match your actual data types and converters
ConvertersByDataType = new Dictionary<DataType, JsonConverter>
{
{ DataType.PostalCode, new PostalCodeConverter() },
{ DataType.PhoneNumber, new PhoneNumberConverter() },
};
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
var att = prop.AttributeProvider.GetAttributes(true).OfType<DataTypeAttribute>().FirstOrDefault();
if (att != null)
{
JsonConverter converter;
if (ConvertersByDataType.TryGetValue(att.DataType, out converter))
{
prop.Converter = converter;
}
}
return prop;
}
}
Then pass the resolver to SerializeObject and/or DeserializeObject via the settings:
var settings = new JsonSerializerSettings
{
ContractResolver = new DataTypeResolver()
};
string json = JsonConvert.SerializeObject(yourObject, settings);
Here is a working demo: https://dotnetfiddle.net/k1kWv5
You can add Converters to the JsonSerializerSettings. So instead of decorating everything, you may as well add your PostcodeJsonConverter there (depending on how often it is used, a decorator may be better though):
For aspnet core defaults:
services.AddMvc().AddJsonOptions(o => o.SerializerSettings.Converters.Add(new PostcodeJsonConverter()))
For JsonConvert:
JsonConvert.SerializeObject(obj, new JsonSerializerSettings
{
Converters = { new PostcodeJsonConverter() }
});

How to force JsonConverter.WriteJson() to be called for a null value

I want to wrap some properties in a JSON object with some metadata, regardless if it's null or not. However, my custom JsonConverter.WriteJson override is not called in case the property is null.
What I get when property is not null:
{"Prop":{"Version":1, "Object":{"Content":"abc"}}}
What I get when it's null:
{"Prop":null}
What I want when it's null:
{"Prop":{"Version":1, "Object":null}}
Due to WriteJson never being called for null values, I do not get the opportunity to control this behavior. Is there any way to force this?
Note that I want to know if this is possible to do with e.g converters or contractresolvers, I can't/don't want to change the MyContent or Wrap classes (see below).
class VersioningJsonConverter : JsonConverter
{
//Does not get called if value is null !!
public override void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName("v");
writer.WriteValue(1);
writer.WritePropertyName("o");
if(value == null)
{
//never happens
writer.WriteNull();
}
else
{
writer.WriteStartObject();
writer.WritePropertyName("Content");
writer.WriteValue((value as MyContent).Content);
writer.WriteEndObject();
}
writer.WriteEndObject();
}
public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
=> throw new NotImplementedException();
public override Boolean CanConvert(Type objectType) => objectType == typeof(MyContent);
public override Boolean CanRead => false;
}
public class MyContent
{
public String Content {get;set;}
}
public class Wrap
{
public MyContent Prop {get;set;}
}
There is no way currently to make Json.NET call JsonConverter.WriteJson() for a null value. This can be seen in JsonSerializerInternalWriter.SerializeValue(...) which immediately writes a null and returns for a null incoming value:
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
// Remainder omitted
So if you need to translate null member(s) to non-null JSON value(s) but cannot modify the types themselves, you have two options:
Create a custom JsonConverter for the parent declaring type(s) of the member(s) that serializes every parent manually, OR
Create a custom contract resolver that translates the member(s) to ones returning some non-null surrogate or wrapper object.
Option #2 is more maintainable. The following contract resolver should do the job, wrapping the returned value of every member returning a value of the type(s) specified in the incoming list of types with the required version information:
public class CustomContractResolver : DefaultContractResolver
{
// Because contracts are cached, WrappedTypes must not be modified after construction.
readonly HashSet<Type> WrappedTypes = new HashSet<Type>();
public CustomContractResolver(IEnumerable<Type> wrappedTypes)
{
if (wrappedTypes == null)
throw new ArgumentNullException();
foreach (var type in wrappedTypes)
WrappedTypes.Add(type);
}
class VersionWrapperProvider<T> : IValueProvider
{
readonly IValueProvider baseProvider;
public VersionWrapperProvider(IValueProvider baseProvider)
{
if (baseProvider == null)
throw new ArgumentNullException();
this.baseProvider = baseProvider;
}
public object GetValue(object target)
{
return new VersionWrapper<T>(target, baseProvider);
}
public void SetValue(object target, object value) { }
}
class ReadOnlyVersionWrapperProvider<T> : IValueProvider
{
readonly IValueProvider baseProvider;
public ReadOnlyVersionWrapperProvider(IValueProvider baseProvider)
{
if (baseProvider == null)
throw new ArgumentNullException();
this.baseProvider = baseProvider;
}
public object GetValue(object target)
{
return new ReadOnlyVersionWrapper<T>(target, baseProvider);
}
public void SetValue(object target, object value) { }
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (WrappedTypes.Contains(property.PropertyType)
&& !(member.DeclaringType.IsGenericType
&& (member.DeclaringType.GetGenericTypeDefinition() == typeof(VersionWrapper<>) || member.DeclaringType.GetGenericTypeDefinition() == typeof(ReadOnlyVersionWrapper<>))))
{
var wrapperGenericType = (property.Writable ? typeof(VersionWrapper<>) : typeof(ReadOnlyVersionWrapper<>));
var providerGenericType = (property.Writable ? typeof(VersionWrapperProvider<>) : typeof(ReadOnlyVersionWrapperProvider<>));
var wrapperType = wrapperGenericType.MakeGenericType(new[] { property.PropertyType });
var providerType = providerGenericType.MakeGenericType(new[] { property.PropertyType });
property.PropertyType = wrapperType;
property.ValueProvider = (IValueProvider)Activator.CreateInstance(providerType, property.ValueProvider);
property.ObjectCreationHandling = ObjectCreationHandling.Reuse;
}
return property;
}
}
internal class VersionWrapper<T>
{
readonly object target;
readonly IValueProvider baseProvider;
public VersionWrapper(object target, IValueProvider baseProvider)
{
this.target = target;
this.baseProvider = baseProvider;
}
public int Version { get { return 1; } }
[JsonProperty(NullValueHandling = NullValueHandling.Include)]
public T Object
{
get
{
return (T)baseProvider.GetValue(target);
}
set
{
baseProvider.SetValue(target, value);
}
}
}
internal class ReadOnlyVersionWrapper<T>
{
readonly object target;
readonly IValueProvider baseProvider;
public ReadOnlyVersionWrapper(object target, IValueProvider baseProvider)
{
this.target = target;
this.baseProvider = baseProvider;
}
public int Version { get { return 1; } }
[JsonProperty(NullValueHandling = NullValueHandling.Include)]
public T Object
{
get
{
return (T)baseProvider.GetValue(target);
}
}
}
Then use it as follows to wrap all properties of type MyContent:
static IContractResolver resolver = new CustomContractResolver(new[] { typeof(MyContent) });
// And later
var settings = new JsonSerializerSettings
{
ContractResolver = resolver,
};
var json = JsonConvert.SerializeObject(wrap, Formatting.Indented, settings);
Notes:
You should statically cache the contract resolver for performance reasons explained here.
VersionWrapperProvider<T> creates a wrapper object with the necessary version information as well as a surrogate Object property that gets and sets the underlying value using Json.NET's own IValueProvider.
Because Json.NET does not set back the value of a pre-allocated reference property, but instead simply populates it with the deserialized property values, it is necessary for the setter of VersionWrapper<T>.Object to itself set the value in the parent.
If your wrapped types are polymorphic, in CreateProperty() you may need to check whether any of the base types of property.PropertyType are in WrappedTypes.
Populating a pre-existing Wrap using JsonConvert.PopulateObject should be tested.
This solution may not work when deserializing properties passed to parameterized constructors. DefaultContractResolver.CreatePropertyFromConstructorParameter would need modification in such a situation.
Working sample .Net fiddle here.

Validate response to filter array objects which are having no elements

How can I filter out the array objects which are having 0 elements from the ASP.NET Web API Model.
Ex: I'm am using the below method to filter null objects.
using Newtonsoft.Json;
public string FaxWork { get; set; }
[JsonProperty(PropertyName = "phoneWork", NullValueHandling = NullValueHandling.Ignore)]
How can I use something like above in order to filter out [] empty array objects?
Ex:
"postalAddress": [],
"electronicAddress": []
You can accomplish this using the conditional property serialization functionality of Json.NET.
If you just want to ignore a single member when its array value is empty, add a ShouldSerialize{PropertyName}() method to your class that returns false when you don't want it serialized, e.g.:
public class RootObject
{
public string[] PostalAddress { get; set; }
public bool ShouldSerializePostalAddress() { return PostalAddress != null && PostalAddress.Length > 0; }
}
If you need to do this for many different collection-valued members of many different types, you can create a custom contract resolver that automatically generates a ShouldSerialize predicate for all of then:
public class SkipEmptyCollectionsContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization)
.AddShouldSerializeEmptyCollections(this);
return property;
}
}
public static class JsonPropertyExtensions
{
public static JsonProperty AddShouldSerializeEmptyCollections(this JsonProperty property, IContractResolver resolver)
{
if (property == null)
throw new ArgumentNullException();
if ((typeof(IEnumerable).IsAssignableFrom(property.PropertyType) || property.PropertyType.IsAssignableFrom(typeof(IEnumerable)))
&& property.PropertyType != typeof(string)
&& property.Readable)
{
Predicate<object> shouldSerialize = (parent) =>
{
var value = property.ValueProvider.GetValue(parent);
if (value == null || value is string)
return true; // null properties are filtered by the NullValueHandling setting.
var contract = resolver.ResolveContract(value.GetType());
if (contract is JsonArrayContract)
{
return (value as IEnumerable).Any();
}
return true;
};
var oldShouldSerialize = property.ShouldSerialize;
if (oldShouldSerialize == null)
property.ShouldSerialize = shouldSerialize;
else
property.ShouldSerialize = (o) => shouldSerialize(o) && oldShouldSerialize(o);
}
return property;
}
}
public static class EnumerableExtensions
{
public static bool Any(this IEnumerable enumerable)
{
if (enumerable == null)
return false;
if (enumerable is ICollection)
{
return ((ICollection)enumerable).Count > 0;
}
var enumerator = enumerable.GetEnumerator();
using (enumerator as IDisposable)
{
return enumerator.MoveNext();
}
}
}
Then serialize using JsonSerializerSettings such as the following, which also enables camel casing of names:
var settings = new JsonSerializerSettings
{
ContractResolver = new SkipEmptyCollectionsContractResolver { NamingStrategy = new CamelCaseNamingStrategy() },
NullValueHandling = NullValueHandling.Ignore,
};
If you want to conditionally filter out empty collections using attributes, you could do so with the following contract resolver and attribute:
public enum EmptyArrayHandling
{
Include = 0,
Ignore = 1,
}
[System.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class JsonPropertyExtensionsAttribute : System.Attribute
{
public EmptyArrayHandling EmptyArrayHandling { get; set; }
}
public class ConditionallySkipEmptyCollectionsContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var attr = property.AttributeProvider.GetAttributes(typeof(JsonPropertyExtensionsAttribute), false).Cast<JsonPropertyExtensionsAttribute>().FirstOrDefault();
if (attr != null && attr.EmptyArrayHandling == EmptyArrayHandling.Ignore)
property = property.AddShouldSerializeEmptyCollections(this);
return property;
}
}
Then apply to your members as follows:
public class RootObject
{
[JsonPropertyExtensions(EmptyArrayHandling = EmptyArrayHandling.Ignore)]
public string[] PostalAddress { get; set; }
}
Note that if your "collection" is actually a complex LINQ query, the ShouldSerialize method will have to enumerate the first element of the query to see if it is empty, which may lead to poor performance because the query will get evaluated twice. To avoid this, you can evaluate the entire query as a list before serializing.
You may want to cache the contract resolver for best performance.

How to add metadata to describe which properties are dates in JSON.Net

I would like to add a metadata property to my json so that the client side can know what properties are dates.
For example if I had an object like this:
{
"notADate": "a value",
"aDate": "2017-04-23T18:25:43.511Z",
"anotherDate": "2017-04-23T18:25:43.511Z"
}
I would like to add a metadata property to tell the consumer which properties to treat as dates something like this:
{
"_date_properties_": ["aDate", "anotherDate"],
"notADate": "a value",
"aDate": "2017-04-23T18:25:43.511Z",
"anotherDate": "2017-04-23T18:25:43.511Z"
}
Any help would be great, thanks!
You could create a custom ContractResolver that inserts a synthetic "_date_properties_" property into the contract of every object that is serialized.
To do this, first subclass DefaultContractResolver to allow contracts to be fluently customized after they have been created by application-added event handlers:
public class ConfigurableContractResolver : DefaultContractResolver
{
readonly object contractCreatedPadlock = new object();
event EventHandler<ContractCreatedEventArgs> contractCreated;
int contractCount = 0;
void OnContractCreated(JsonContract contract, Type objectType)
{
EventHandler<ContractCreatedEventArgs> created;
lock (contractCreatedPadlock)
{
contractCount++;
created = contractCreated;
}
if (created != null)
{
created(this, new ContractCreatedEventArgs(contract, objectType));
}
}
public event EventHandler<ContractCreatedEventArgs> ContractCreated
{
add
{
lock (contractCreatedPadlock)
{
if (contractCount > 0)
{
throw new InvalidOperationException("ContractCreated events cannot be added after the first contract is generated.");
}
contractCreated += value;
}
}
remove
{
lock (contractCreatedPadlock)
{
if (contractCount > 0)
{
throw new InvalidOperationException("ContractCreated events cannot be removed after the first contract is generated.");
}
contractCreated -= value;
}
}
}
protected override JsonContract CreateContract(Type objectType)
{
var contract = base.CreateContract(objectType);
OnContractCreated(contract, objectType);
return contract;
}
}
public class ContractCreatedEventArgs : EventArgs
{
public JsonContract Contract { get; private set; }
public Type ObjectType { get; private set; }
public ContractCreatedEventArgs(JsonContract contract, Type objectType)
{
this.Contract = contract;
this.ObjectType = objectType;
}
}
public static class ConfigurableContractResolverExtensions
{
public static ConfigurableContractResolver Configure(this ConfigurableContractResolver resolver, EventHandler<ContractCreatedEventArgs> handler)
{
if (resolver == null || handler == null)
throw new ArgumentNullException();
resolver.ContractCreated += handler;
return resolver;
}
}
Next, create an extension method to add the desired property to a JsonObjectContract:
public static class JsonContractExtensions
{
const string DatePropertiesName = "_date_properties_";
public static void AddDateProperties(this JsonContract contract)
{
var objectContract = contract as JsonObjectContract;
if (objectContract == null)
return;
var properties = objectContract.Properties.Where(p => p.PropertyType == typeof(DateTime) || p.PropertyType == typeof(DateTime?)).ToList();
if (properties.Count > 0)
{
var property = new JsonProperty
{
DeclaringType = contract.UnderlyingType,
PropertyName = DatePropertiesName,
UnderlyingName = DatePropertiesName,
PropertyType = typeof(string[]),
ValueProvider = new FixedValueProvider(properties.Select(p => p.PropertyName).ToArray()),
AttributeProvider = new NoAttributeProvider(),
Readable = true,
Writable = false,
// Ensure // Ensure PreserveReferencesHandling and TypeNameHandling do not apply to the synthetic property.
ItemIsReference = false,
TypeNameHandling = TypeNameHandling.None,
};
objectContract.Properties.Insert(0, property);
}
}
class FixedValueProvider : IValueProvider
{
readonly object properties;
public FixedValueProvider(object value)
{
this.properties = value;
}
#region IValueProvider Members
public object GetValue(object target)
{
return properties;
}
public void SetValue(object target, object value)
{
throw new NotImplementedException("SetValue not implemented for fixed properties; set JsonProperty.Writable = false.");
}
#endregion
}
class NoAttributeProvider : IAttributeProvider
{
#region IAttributeProvider Members
public IList<Attribute> GetAttributes(Type attributeType, bool inherit) { return new Attribute[0]; }
public IList<Attribute> GetAttributes(bool inherit) { return new Attribute[0]; }
#endregion
}
}
Finally, serialize your example type as follows:
var settings = new JsonSerializerSettings
{
ContractResolver = new ConfigurableContractResolver
{
// Here I am using CamelCaseNamingStrategy as is shown in your JSON.
// If you don't want camel case, leave NamingStrategy null.
NamingStrategy = new CamelCaseNamingStrategy(),
}.Configure((s, e) => { e.Contract.AddDateProperties(); }),
};
var json = JsonConvert.SerializeObject(example, Formatting.Indented, settings);
This solution only handles statically typed DateTime and DateTime? properties. If you have object-valued properties that sometimes have DateTime values, or a Dictionary<string, DateTime>, or extension data containing DateTime values, you will need a more complex solution.
(As an alternative implementation, you could instead subclass DefaultContractResolver.CreateObjectContract and hardcode the required properties there using JsonContractExtensions.AddDateProperties(), however I thought it would be more interesting to create a general-purpose, fluently configurable contract resolver in case it becomes necessary to plug in different customizations later.)
You may want to cache the contract resolver for best performance.
Sample .Net fiddle.

Categories

Resources