https://stackoverflow.com/questions/53736394/convert-c-sharp-class-to-json-with-customized-structure

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/53736394/convert-c-sharp-class-to-json-with-customized-structure
    public class NestedValueConverter<T> : JsonConverter
    {
        class Value
        {
            public T value { get; set; }
        }

        public override bool CanConvert(Type objectType)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            switch (reader.MoveToContent().TokenType)
            {
                case JsonToken.Null:
                    return null;

                default:
                    return serializer.Deserialize<Value>(reader).value;
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, new Value { value = (T)value });
        }
    }

    public static partial class JsonExtensions
    {
        public static JsonReader MoveToContent(this JsonReader reader)
        {
            if (reader.TokenType == JsonToken.None)
                reader.Read();
            while (reader.TokenType == JsonToken.Comment && reader.Read())
                ;
            return reader;
        }
    }

    public class PrimaryContact
    {
        [JsonConverter(typeof(NestedValueConverter<string>))]
        public string PrefixTitle { get; set; }

        public string SurName { get; set; }

        public string GivenName { get; set; }
    }

	public class RootObject
	{
		public PrimaryContact PrimaryContact { get; set; }
	}

    class TestClass
    {
        public static void Test()
        {
			var jsonString = GetJson();
			
			var settings = new JsonSerializerSettings
			{
				ContractResolver = new CamelCasePropertyNamesContractResolver(),
			};
			var root = JsonConvert.DeserializeObject<RootObject>(jsonString, settings);
			
			var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);
			
			Console.WriteLine(json2);

			Assert.IsTrue(JToken.DeepEquals(JToken.Parse(jsonString), JToken.Parse(json2)));

			Assert.IsTrue(root.PrimaryContact.PrefixTitle == "mrs");
		}	
		
		static string GetJson()
		{
			var json = @"{
""primaryContact"": {
      ""prefixTitle"": {
        ""value"": ""mrs""
      },
      ""surName"": ""abcd"",
      ""givenName"": ""abcd""      
    }
}
";
			return json;
		}
	}

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