CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.Serialization;
using System.Data;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
// https://stackoverflow.com/questions/44364361/json-conversion-in-asp-net-for-cqrs
public abstract class ServicePropertyBase
{
public abstract object GetValue();
}
// Possibly this class should be sealed.
public class ServiceProperty<T> : ServicePropertyBase
{
public ServiceProperty() { }
public ServiceProperty(T value) { this.Value = value; }
public T Value { get; set; }
public override object GetValue()
{
return Value;
}
}
public class ServicePropertyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.GetServicePropertyValueType() != null;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var valueType = objectType.GetServicePropertyValueType();
var value = serializer.Deserialize(reader, valueType);
// Use the parameterized constructor.
return Activator.CreateInstance(objectType, value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var baseValue = (ServicePropertyBase)value;
serializer.Serialize(writer, baseValue.GetValue());
}
}
internal static class ServicePropertyExtensions
{
public static Type GetServicePropertyValueType(this Type objectType)
{
if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ServiceProperty<>))
{
return objectType.GetGenericArguments()[0];
}
return null;
}
}
public class ServicePropertyContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.DefaultValueHandling == null && property.PropertyType.GetServicePropertyValueType() != null)
{
property.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
}
return property;
}
}
public class RootObject
{
public ServiceProperty<string> StringValue { get; set; }
public ServiceProperty<int> IntValue { get; set; }
public ServiceProperty<int?> NullableValue { get; set; }
public ServiceProperty<RootObject> RootObjectValue { get; set; }
}
class TestClass
{
public static void Test()
{
Test(new RootObject());
Test(new RootObject
{
StringValue = new ServiceProperty<string>(),
IntValue = new ServiceProperty<int>(),
NullableValue = new ServiceProperty<int?>(),
RootObjectValue = new ServiceProperty<RootObject>(),
});
Test(new RootObject
{
StringValue = new ServiceProperty<string>("hello"),
IntValue = new ServiceProperty<int>(121),
NullableValue = new ServiceProperty<int?>(232),
RootObjectValue = new ServiceProperty<RootObject>(new RootObject()),
});
}
static void Test(RootObject model)
{
var settings1 = new JsonSerializerSettings
{
Converters = { new ServicePropertyConverter() },
Formatting = Formatting.Indented,
//NullValueHandling.Ignore cannot be used because ServicePropertyConverter.ReadJson()
//will not get called during reading to allocate an empty ServiceProperty<T>.
//NullValueHandling = NullValueHandling.Ignore,
//Instead DefaultValueHandling.IgnoreAndPopulate must be used to skip serialization
//of a null ServiceProperty<T> when serializing but force ServicePropertyConverter.ReadJson()
//to be called when deserializing.
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
};
Test(model, settings1);
var settings2 = new JsonSerializerSettings
{
Converters = { new ServicePropertyConverter() },
Formatting = Formatting.Indented,
ContractResolver = new ServicePropertyContractResolver(),
};
Test(model, settings2);
}
static void Test(RootObject model, JsonSerializerSettings settings)
{
var json = JsonConvert.SerializeObject(model, settings);
Console.WriteLine("Serialized JSON for {0}", model);
Console.WriteLine(json);
var model2 = JsonConvert.DeserializeObject<RootObject>(json, settings);
var json2 = JsonConvert.SerializeObject(model2, settings);
Console.WriteLine("Deserialied and re-serialized JSON for {0}", model2);
Console.WriteLine(json2);
Assert.IsTrue(json == json2);
Console.WriteLine();
}
}
public static class Assert
{
public static void IsTrue(bool value)
{
if (value == false)
throw new AssertionFailedException("failed");
}
}
public class AssertionFailedException : System.Exception
{
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("");
TestClass.Test();
}
}