[Fork] [Fork] questions/52721999/modelstate-error-newtonsoft-json-jsonserializationexception-cannot-populate-l?noredirect=1#comment92399021_52721999

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.Specialized;

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/52721999/modelstate-error-newtonsoft-json-jsonserializationexception-cannot-populate-l?noredirect=1#comment92399021_52721999

    public class NotificationDTO
    {
        public long idCompanyService { get; set; }

        //public DocTypeEnum DocumentType { get; set; }

        public List<Tuple<string, byte[], System.Net.Mime.ContentType>> Attachments { get; set; }
    }

    public class StringDictionaryConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(StringDictionary).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var tokenType = reader.SkipComments().TokenType;
            if (tokenType == JsonToken.Null)
                return null;

            var dictionary = existingValue as StringDictionary ?? (StringDictionary)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();

            switch (tokenType)
            {
                case JsonToken.StartArray:
                    {
                        // StringDictionary serialized without converter
                        var list = serializer.Deserialize<List<KeyValuePair<string, string>>>(reader);
                        foreach (var pair in list)
                            dictionary.Add(pair.Key, pair.Value);
                    }
                    break;

                case JsonToken.StartObject:
                    {
                        // StringDictionary serialized with converter
                        var typedDictionary = serializer.Deserialize<Dictionary<string, string>>(reader);
                        foreach (var pair in typedDictionary)
                            dictionary.Add(pair.Key, pair.Value);
                    }
                    break;

                default:
                    throw new JsonSerializationException(string.Format("Unknown token {0} at path {1}", tokenType, reader.Path));
            }

            return dictionary;
        }

        // Change to false if you want the dictionary written as an array of key/value objects.
        public override bool CanWrite { get { return true; } }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var dictionary = (StringDictionary)value;
            writer.WriteStartObject();
            foreach (DictionaryEntry entry in dictionary)
            {
                writer.WritePropertyName((string)entry.Key);
                writer.WriteValue((string)entry.Value);
            }
            writer.WriteEndObject();
        }
    }

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

    class TestClass
    {
        public static void Test()
        {
            TestStringDictionary();
            TestSimple();
            TestFull();
        }

        static void TestStringDictionary()
        {
            StringDictionary myCol = new StringDictionary();
            myCol.Add("red", "rojo");
            myCol.Add("green", "verde");
            myCol.Add("blue", "azul");

            var settings = new JsonSerializerSettings
            {
                Converters = { new StringDictionaryConverter() },
            };

            var json = JsonConvert.SerializeObject(myCol, settings);
                
            Console.WriteLine(json);

            var myCol2 = JsonConvert.DeserializeObject<StringDictionary>(json, settings);

            Assert.IsTrue(myCol.Count == myCol2.Count);

            var json2 = JsonConvert.SerializeObject(myCol2, settings);

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

            var json3 = JsonConvert.SerializeObject(myCol2);

            Console.WriteLine(json3);

            var myCol3 = JsonConvert.DeserializeObject<StringDictionary>(json, settings);

            var json4 = JsonConvert.SerializeObject(myCol2, settings);

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json4)));
        }


        static void TestSimple()
        {
            var settings = new JsonSerializerSettings
            {
                Converters = { new StringDictionaryConverter() },
            };

            var json = @"{""Boundary"":null,""CharSet"":null,""MediaType"":""application/pdf"",""Name"":null,""Parameters"":[]}";

            var content = JsonConvert.DeserializeObject<System.Net.Mime.ContentType>(json, settings);

            var json2 = JsonConvert.SerializeObject(content, Formatting.Indented, settings);

            Console.WriteLine("\nResult of trying to deserialize and re-serialize a {0}: ", typeof(System.Net.Mime.ContentType));

            Console.WriteLine(json2);
        }

        public static void TestFull()
        {
            var json = @"{""idCompanyService"":1234,""DocumentType"":1,""Attachments"":[{""Item1"":""wqere.pdf"",""Item2"":""TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="",""Item3"":{""Boundary"":null,""CharSet"":null,""MediaType"":""application/pdf"",""Name"":null,""Parameters"":[]}},{""Item1"":""ewqeqwe.xml"",""Item2"":""TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="",""Item3"":{""Boundary"":null,""CharSet"":null,""MediaType"":""text/xml"",""Name"":null,""Parameters"":[]}}]}";


            var settings = new JsonSerializerSettings
            {
                Converters = { new StringDictionaryConverter() },
            };

            var dto = JsonConvert.DeserializeObject<NotificationDTO>(json, settings);

            var json2 = JsonConvert.SerializeObject(dto, Formatting.Indented, settings);

            Console.WriteLine("\nResult of trying to deserialize and re-serialize a {0}: ",  typeof(NotificationDTO));
			
            Console.WriteLine(json2);
        }
    }

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