Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #257 from kongo2002/nullable_enum

Nullable enums do not respect the [Flags] attribute
  • Loading branch information...
commit 15469019f75627c50364b32a40ec7ca78cc2fb41 2 parents 1de1b89 + 74034cb
@desunit desunit authored
View
8 src/ServiceStack.Text/Common/JsWriter.cs
@@ -228,7 +228,13 @@ public WriteObjectDelegate GetValueTypeToStringMethod(Type type)
return Serializer.WriteDecimal;
if (type.IsEnum || type.UnderlyingSystemType.IsEnum)
- return type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0
+ return type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0
+ ? (WriteObjectDelegate)Serializer.WriteEnumFlags
+ : Serializer.WriteEnum;
+
+ Type nullableType;
+ if ((nullableType = Nullable.GetUnderlyingType(type)) != null && nullableType.IsEnum)
+ return nullableType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0
? (WriteObjectDelegate)Serializer.WriteEnumFlags
: Serializer.WriteEnum;
View
54 tests/ServiceStack.Text.Tests/EnumTests.cs
@@ -0,0 +1,54 @@
+using System;
+using NUnit.Framework;
+
+namespace ServiceStack.Text.Tests
+{
+ [TestFixture]
+ public class EnumTests
+ {
+ [SetUp]
+ public void SetUp()
+ {
+ JsConfig.Reset();
+ }
+
+ public enum EnumWithoutFlags
+ {
+ One = 1,
+ Two = 2
+ }
+
+ [Flags]
+ public enum EnumWithFlags
+ {
+ One = 1,
+ Two = 2
+ }
+
+ public class ClassWithEnums
+ {
+ public EnumWithFlags FlagsEnum { get; set; }
+ public EnumWithoutFlags NoFlagsEnum { get; set; }
+ public EnumWithFlags? NullableFlagsEnum { get; set; }
+ public EnumWithoutFlags? NullableNoFlagsEnum { get; set; }
+ }
+
+ [Test]
+ public void Can_correctly_serialize_enums()
+ {
+ var item = new ClassWithEnums
+ {
+ FlagsEnum = EnumWithFlags.One,
+ NoFlagsEnum = EnumWithoutFlags.One,
+ NullableFlagsEnum = EnumWithFlags.Two,
+ NullableNoFlagsEnum = EnumWithoutFlags.Two
+ };
+
+ const string expected = "{\"FlagsEnum\":1,\"NoFlagsEnum\":\"One\",\"NullableFlagsEnum\":2,\"NullableNoFlagsEnum\":\"Two\"}";
+ var text = JsonSerializer.SerializeToString(item);
+
+ Assert.AreEqual(expected, text);
+ }
+ }
+}
+
View
1  tests/ServiceStack.Text.Tests/ServiceStack.Text.Tests.csproj
@@ -172,6 +172,7 @@
<Compile Include="CyclicalDependencyTests.cs" />
<Compile Include="DynamicModels\GoogleMapsApiTests.cs" />
<Compile Include="DateTimeOffsetAndTimeSpanTests.cs" />
+ <Compile Include="EnumTests.cs" />
<Compile Include="JsonTests\BasicPropertiesTests.cs" />
<Compile Include="JsonObjectTests.cs" />
<Compile Include="JsonTests\AnonymousDeserializationTests.cs" />
Please sign in to comment.
Something went wrong with that request. Please try again.