questions/48297038/newtonsoft-deserializeobject-not-calling-contructor

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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

    // https://stackoverflow.com/questions/48297038/newtonsoft-deserializeobject-not-calling-contructor
    public class ApiResponse<T> where T : class
    {
        public bool Errors { get; set; }
        public T Response { get; set; }
    }
    public class ApiPagingResponse<T> : ApiResponse<T> where T : class
    {
        //public Pagination Pagination { get; set; }
    }
    public class GetBalanceListResponse
    {
        // public GetBalanceListResponseEntity Entity { get; set; }
        public List<GetBalanceListResponseEntity> Entities { get; set; }
    }
    [JsonObject]
    public class GetBalanceListResponseEntity
    {

        [JsonConstructor]
        public GetBalanceListResponseEntity([JsonProperty("currency_id")]string currencyId, [JsonProperty("balance")]string balance, [JsonProperty("address")]string address)
        {
            CurrencyId = currencyId;
            Balance = decimal.Parse(balance, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint,
                CultureInfo.InvariantCulture);
            Address = address;
        }

        [JsonProperty("currency_id")]
        public string CurrencyId { get; set; }

        [JsonProperty("balance")]
        public decimal Balance { get; set; }

        [JsonProperty("address")]
        public string Address { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
            Test(GetSimpleJson());
            Test(GetJson());

            Console.WriteLine("\nDone.");
        }
        public static void Test(string json)
        {
            Console.WriteLine("\nInput JSON: ");
            Console.WriteLine(json);

            var root = JsonConvert.DeserializeObject<ApiPagingResponse<GetBalanceListResponse>>(json);
            var json2 = JsonConvert.SerializeObject(root, Formatting.Indented);

            Console.WriteLine("Deserialized and re-serialized JSON: ");
            Console.WriteLine(json2);
        }

        static string GetSimpleJson()
        {
            var json = @"{
    ""errors"": false,
    ""response"": {
        ""entities"": [
        {
            ""currency_id"": ""1"",
            ""balance"": 1e-8,
            ""address"": """"
        }]
    },
    ""pagination"": {
        ""items_per_page"": 100,
        ""total_items"": 5,
        ""current_page"": 1,
        ""total_pages"": 1
   }
}";
            return json;
        }

        static string GetJson()
        {
            var json = @"{
    ""errors"": false,
    ""response"": {
        ""entities"": [
        {
            ""currency_id"": ""1"",
            ""balance"": 1e-8,
            ""address"": """"
        },
        {
            ""currency_id"": ""2"",
            ""balance"": 0,
            ""address"": null
        },
        {
            ""currency_id"": ""3"",
            ""balance"": 0.09865566,
            ""address"": null
        },
        {
            ""currency_id"": ""5"",
            ""balance"": 0,
            ""address"": null
        },
        {
            ""currency_id"": ""6"",
            ""balance"": 0,
            ""address"": null
        }]
    },
    ""pagination"": {
        ""items_per_page"": 100,
        ""total_items"": 5,
        ""current_page"": 1,
        ""total_pages"": 1
   }
}";
            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;
			}
		}
	}

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }
;