https://stackoverflow.com/questions/53768041/custom-serializer-for-just-one-property-in-json-net-without-changing-the-model

CSharp · Console

/Program.cs

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/53768041/custom-serializer-for-just-one-property-in-json-net-without-changing-the-model
    public class ConfigurableContractResolver : DefaultContractResolver
    {
        // This contract resolver taken from the answer to
        // https://stackoverflow.com/questions/46047308/how-to-add-metadata-to-describe-which-properties-are-dates-in-json-net
        // https://stackoverflow.com/a/46083201/3744182

        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;
        }
    }

	public class Person
	{
		public string FirstName { get; set; }

		//[JsonConverter(typeof(AllCapsConverter))]
		public string LastName { get; set; }
		// more properties here in the real example, some of which nest to properties that use their own JsonConverters.
	}

	public class AllCapsConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType) { return objectType == typeof(string); }

        public override bool CanRead { get { return false; } }

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			throw new NotSupportedException();
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var str = value as string;
			var upper = str.ToUpperInvariant();
			writer.WriteValue(upper);
		}
	}

    public static class JsonContractExtensions
    {
        public static void ConfigurePerson(this JsonContract contract)
        {
			if (!typeof(Person).IsAssignableFrom(contract.UnderlyingType))
				return;
			var objectContract = contract as JsonObjectContract;
            if (objectContract == null)
                return;
			// Use nameof in in .Net 4.5 or later
            //var property = objectContract.Properties.Where(p => p.UnderlyingName == nameof(Person.LastName)).Single();
            var property = objectContract.Properties.Where(p => p.UnderlyingName == "LastName").Single();
			property.Converter = new AllCapsConverter();
        }
	}

    class TestClass
    {
        public static void Test()
        {
			// Cache the contract resolver statically for best performance.
            var resolver = new ConfigurableContractResolver()
                .Configure((s, e) => { e.Contract.ConfigurePerson(); });

            var settigs = new JsonSerializerSettings
            {
                ContractResolver = resolver,
            };

            var person = new Person
            {
                FirstName = "George",
                LastName = "Washington"
            };
            var serialized = JsonConvert.SerializeObject(person, settigs);
            var expected = @"{""FirstName"":""George"",""LastName"":""WASHINGTON""}";
            Assert.AreEqual(expected, serialized);

			Console.WriteLine(serialized);
        }			
	}

	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;
			}
		}
	}
;