CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/53401189/c-sharp-jsonconvert-using-the-default-converter-instead-of-the-custom-converter
//https://stackoverflow.com/questions/53401189/c-sharp-jsonconvert-using-the-default-converter-instead-of-the-custom-converter
public class ConverterDisablingContractResolver : DefaultContractResolver
{
readonly HashSet<Type> types;
public ConverterDisablingContractResolver(IEnumerable<Type> types)
{
if (types == null)
throw new ArgumentNullException();
this.types = new HashSet<Type>(types);
}
bool ContainsType(Type type)
{
return types.Contains(type);
}
protected override JsonConverter ResolveContractConverter(Type objectType)
{
// This could be enhanced to deal with inheritance. I.e. if TBase is in types and has a converter then
// its converter should not be used for TDerived -- but if TDerived has its own converter then it should still be
// used, so simply returning null for TDerived would be wrong.
if (types.Contains(objectType))
return null;
return base.ResolveContractConverter(objectType);
}
}
public interface IShape
{
string Value { get; set; }
}
[JsonConverter(typeof(TheShapeSerializer))]
public class TheShape : IShape
{
public string Value { get; set; }
}
class TheShapeSerializer : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
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)
{
throw new NotImplementedException();
}
}
public class ShapeContainer
{
[JsonConverter(typeof(NoConverter))]
public TheShape Shape { get; set; }
[JsonProperty(ItemConverterType = typeof(NoConverter))]
public List<TheShape> Shapes { get; set; }
}
class TestClass
{
public static void Test()
{
var shape = new TheShape { Value = "my value" };
TestShapeContainer(shape);
TestContractResolver(shape);
try
{
Console.WriteLine("Trying to directly serialize a {0}...", shape);
JsonConvert.SerializeObject(shape);
// Should not come here.
Assert.IsTrue(false);
}
catch (NotImplementedException ex)
{
Console.WriteLine(" ...caught expected exception {0}", ex.Message);
}
Console.WriteLine("\nAll tests passed.");
}
static IContractResolver shapeResolver = new ConverterDisablingContractResolver(new[] { typeof(TheShape) });
static void TestShapeContainer(TheShape shape)
{
var root = new ShapeContainer
{
Shape = shape,
Shapes = new List<TheShape> { shape, shape },
};
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
static void TestContractResolver(TheShape shape)
{
var root = new
{
Shape = shape,
Shapes = new[] { shape, shape },
};
var settings = new JsonSerializerSettings
{
ContractResolver = shapeResolver,
};
var json = JsonConvert.SerializeObject(root, settings);
Console.WriteLine(json);
}
}
public class NoConverter : JsonConverter
{
// Taken from https://stackoverflow.com/questions/39738714/selectively-use-default-json-converter/39739105#39739105
public override bool CanConvert(Type objectType)
{
// Note - not called when attached directly via [JsonConverter(typeof(NoConverter))]
throw new NotImplementedException();
}
public override bool CanRead { get { return false; } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}