https://stackoverflow.com/questions/66464121/how-to-reformat-json-to-mymodel

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 System.Collections.ObjectModel;

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/66464121/how-to-reformat-json-to-mymodel

	public class UserPtr
	{
		public int my_var1 { get; set; }
		public int my_var2 { get; set; }
		public int my_var3 { get; set; }
		public int my_var4 { get; set; }
	}

	public class NamePtrPropertyArrayConverter<T> : JsonConverter<T> where T : class, new()
	{
		struct NamePtrDTO
		{
			public string name;
			public object ptr;
		}
		
		public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
		{
			var obj = (JObject)JsonExtensions.DefaultFromObject(serializer, value);
			serializer.Serialize(writer, obj.Properties().Select(p => new NamePtrDTO { name = p.Name, ptr = p.Value }));
		}

		public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			if (reader.MoveToContentAndAssert().TokenType == JsonToken.Null)
				return null;
			var array = serializer.Deserialize<List<NamePtrDTO>>(reader);
			var obj = new JObject(array.Select(i => new JProperty(i.name, i.ptr)));
        	existingValue = existingValue ?? (T)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
			using (var subReader = obj.CreateReader())
				serializer.Populate(subReader, existingValue);
			return existingValue;
		}
	}

    public static partial class JsonExtensions
    {
        public static JsonReader MoveToContentAndAssert(this JsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException();
            if (reader.TokenType == JsonToken.None)       // Skip past beginning of stream.
                reader.ReadAndAssert();
            while (reader.TokenType == JsonToken.Comment) // Skip past comments.
                reader.ReadAndAssert();
            return reader;
        }

        public static JsonReader ReadAndAssert(this JsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException();
            if (!reader.Read())
                throw new JsonReaderException("Unexpected end of JSON stream.");
            return reader;
        }

		// DefaultFromObject() taken from this answer https://stackoverflow.com/a/29720068/3744182
		// By https://stackoverflow.com/users/3744182/dbc
		// To https://stackoverflow.com/questions/29719509/json-net-throws-stackoverflowexception-when-using-jsonconvert
		
		public static JToken DefaultFromObject(this JsonSerializer serializer, object value)
		{
			if (value == null)
				return JValue.CreateNull();
			var dto = Activator.CreateInstance(typeof(DefaultSerializationDTO<>).MakeGenericType(value.GetType()), value);
			var root = JObject.FromObject(dto, serializer);
			return root["Value"].RemoveFromLowestPossibleParent() ?? JValue.CreateNull();
		}

		public static JToken RemoveFromLowestPossibleParent(this JToken node)
		{
			if (node == null)
				return null;
			// If the parent is a JProperty, remove that instead of the token itself.
			var contained = node.Parent is JProperty ? node.Parent : node;
			contained.Remove();
			// Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should
			if (contained is JProperty)
				((JProperty)node.Parent).Value = null;
			return node;
		}

		interface IHasValue
		{
			object GetValue();
		}

		[JsonObject(NamingStrategyType = typeof(DefaultNamingStrategy), IsReference = false)]
		class DefaultSerializationDTO<T> : IHasValue
		{
			public DefaultSerializationDTO(T value) => this.Value = value;
			public DefaultSerializationDTO() { }
			[JsonConverter(typeof(NoConverter)), JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Serialize)]
			public T Value { get; set; }
			object IHasValue.GetValue() => Value;
		}		
    }

	public class NoConverter : JsonConverter
	{
		// NoConverter taken from this answer https://stackoverflow.com/a/39739105/3744182
		// By https://stackoverflow.com/users/3744182/dbc
		// To https://stackoverflow.com/questions/39738714/selectively-use-default-json-converter
		public override bool CanConvert(Type objectType)  { throw new NotImplementedException(); /* This converter should only be applied via attributes */ }

		public override bool CanRead => false;

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => throw new NotImplementedException();

		public override bool CanWrite => false;

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
	}
	
	[JsonConverter(typeof(NamePtrPropertyArrayConverter<UserPtrComplex>))]
	public class UserPtrComplex
	{
		public int my_var1 { get; set; }
		public string my_var2 { get; set; }
		public int my_var3 { get; set; }
		public UserPtr my_var4 { get; set; }
	}

    class TestClass
    {
        public static void Test()
		{
			TestUserPtr();
			Console.WriteLine();
			TestUserPtrComplex();
		}
		
        public static void TestUserPtr()
        {
			var strJson = GetJson(); 

			var settings = new JsonSerializerSettings
			{
				Converters = { new NamePtrPropertyArrayConverter<UserPtr>() },
			};
			var model = JsonConvert.DeserializeObject<UserPtr>(strJson, settings);
			
			var json21 = JsonConvert.SerializeObject(model, Formatting.Indented, settings);
			var json22 = JsonConvert.SerializeObject(model, Formatting.Indented);
			
			Console.WriteLine("Re-serialized {0}:", model);
			Console.WriteLine(json21);
			Console.WriteLine(json22);
		}	
		
        public static void TestUserPtrComplex()
        {
			var model = new UserPtrComplex
			{
				my_var1 = 1,
				my_var2 = "2",
				my_var3 = 3,
				my_var4 = new UserPtr { my_var1 = 1, my_var2 = 2, my_var3 = 3, my_var4 = 4 },
			};
			
			var settings = new JsonSerializerSettings
			{
			};

			var json = JsonConvert.SerializeObject(model, Formatting.Indented, settings);

			var model2 = JsonConvert.DeserializeObject<UserPtrComplex>(json, settings);
			
			var json2 = JsonConvert.SerializeObject(model2, Formatting.Indented);
			
			Console.WriteLine("Serialized {0}:", model);
			Console.WriteLine(json);
			Console.WriteLine("Re-serialized {0}:", model2);
			Console.WriteLine(json2);
		}
		
		static string GetJson()
		{
			return @"// Test comment
[ 
    {
        ""name"": ""my_var1"",
        ""ptr"": 1
    },// Test comment
    {
        ""name"": ""my_var2"",
        ""ptr"": 2 // Test comment
    },
    {
        ""name"": ""my_var3"",
        ""ptr"": 2
    },
    {
        ""name"": ""my_var4"",
        ""ptr"": 4
    }
]
";
		}
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name,  typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
		
		public static string GetNetCoreVersion()
		{
			//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
			//
			var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
			var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
			if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
				return assemblyPath[netCoreAppIndex + 1];
			return null;
		}
	}
;