From 6160ea50658cfcbb9cae1578ed3ff6fe55716ad0 Mon Sep 17 00:00:00 2001 From: Harald Wolff Date: Sat, 12 Dec 2020 20:16:54 +0100 Subject: [PATCH] fix bug in JSONMapper triggered by serializing enums based on smaller types then int (e.g. ushort) - added testcase for enum serialization --- ln.json.tests/JSONTests.cs | 65 +++++++++++++++++++++++++++++++++++ ln.json/mapping/JSONMapper.cs | 6 ++-- 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/ln.json.tests/JSONTests.cs b/ln.json.tests/JSONTests.cs index f4e7ba9..23dc3c0 100644 --- a/ln.json.tests/JSONTests.cs +++ b/ln.json.tests/JSONTests.cs @@ -1,9 +1,31 @@ +using System; +using ln.json.mapping; using NUnit.Framework; namespace ln.json.tests { public class JSONTests { + + enum testEnum1 { A, B, C, D, E, F } + enum testEnum2 : ushort { + NONE = 0, + A = 1, + B = 2, + C = 4, + D = 5, + E = 6 + } + [Flags] + enum testEnum3 : ushort { + NONE = 0, + A = 1, + B = 2, + C = 4, + D = 5, + E = 6 + } + [SetUp] public void Setup() { @@ -42,5 +64,48 @@ namespace ln.json.tests JSONParser.Parse("{\t}"); } + [Test] + public void TestEnumMappings() + { + TestEnumSerialization(testEnum1.A); + TestEnumSerialization(testEnum1.B); + TestEnumSerialization(testEnum1.C); + TestEnumSerialization(testEnum1.D); + TestEnumSerialization(testEnum1.E); + TestEnumSerialization(testEnum1.F); + + TestEnumSerialization(testEnum2.NONE); + TestEnumSerialization(testEnum2.A); + TestEnumSerialization(testEnum2.B); + TestEnumSerialization(testEnum2.C); + TestEnumSerialization(testEnum2.D); + TestEnumSerialization(testEnum2.E); + + TestEnumSerialization(testEnum3.NONE); + TestEnumSerialization(testEnum3.A); + TestEnumSerialization(testEnum3.B); + TestEnumSerialization(testEnum3.C); + TestEnumSerialization(testEnum3.D); + TestEnumSerialization(testEnum3.E); + + + } + + bool TestEnumSerialization(object enumValue) + { + Type enumType = enumValue.GetType(); + + Assert.IsTrue(JSONMapper.DefaultMapper.Serialize(enumValue, out JSONValue jsonEnum)); + + JSONMapper.DefaultMapper.Deserialize(jsonEnum, enumType, out object enunValueDeserialized); + + Assert.AreEqual(enumType, enunValueDeserialized.GetType()); + Assert.AreEqual(enumValue, enunValueDeserialized); + + return true; + } + + + } } \ No newline at end of file diff --git a/ln.json/mapping/JSONMapper.cs b/ln.json/mapping/JSONMapper.cs index 55111a8..f5cfa11 100644 --- a/ln.json/mapping/JSONMapper.cs +++ b/ln.json/mapping/JSONMapper.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using System.Text; namespace ln.json.mapping { @@ -157,7 +156,10 @@ namespace ln.json.mapping { if (type.GetCustomAttribute() != null) { - json = new JSONNumber((int)o); + Type enumBaseType = type.GetEnumUnderlyingType(); + o = Convert.ChangeType(o, enumBaseType); + ConstructorInfo constructor = typeof(JSONNumber).GetConstructor(new Type[]{ enumBaseType }); + json = (JSONNumber)constructor.Invoke(new object[]{ o }); } else {