Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit d783775

Browse files
committed
Support deserializing '0' and '1' for boolean values
1 parent d22ad4b commit d783775

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/ServiceStack.Text/Common/DeserializeBuiltin.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ private static ParseStringDelegate GetParseFn()
3232
{
3333
//Note the generic typeof(T) is faster than using var type = typeof(T)
3434
if (typeof(T) == typeof(bool))
35-
return value => bool.Parse(value);
35+
return value => value.Length == 1 ? value == "1" : bool.Parse(value);
3636
if (typeof(T) == typeof(byte))
3737
return value => byte.Parse(value);
3838
if (typeof(T) == typeof(sbyte))
@@ -79,7 +79,7 @@ private static ParseStringDelegate GetParseFn()
7979
return value => ulong.Parse(value);
8080

8181
if (typeof(T) == typeof(bool?))
82-
return value => string.IsNullOrEmpty(value) ? (bool?)null : bool.Parse(value);
82+
return value => string.IsNullOrEmpty(value) ? (bool?)null : value.Length == 1 ? value == "1" : bool.Parse(value);
8383
if (typeof(T) == typeof(byte?))
8484
return value => string.IsNullOrEmpty(value) ? (byte?)null : byte.Parse(value);
8585
if (typeof(T) == typeof(sbyte?))

tests/ServiceStack.Text.Tests/BclStructTests.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Drawing;
3+
using System.Runtime.Serialization;
34
using NUnit.Framework;
45
using ServiceStack.Common;
56

@@ -76,5 +77,28 @@ public void Can_serialize_dto_with_enum_flags()
7677

7778
Assert.That(deserialized.Enum, Is.EqualTo(ExampleEnum.One | ExampleEnum.Four));
7879
}
79-
}
80+
81+
[DataContract]
82+
public class Item
83+
{
84+
[DataMember(Name = "favorite")]
85+
public bool IsFavorite { get; set; }
86+
}
87+
88+
[Test]
89+
public void Can_customize_bool_deserialization()
90+
{
91+
var dto1 = "{\"favorite\":1}".FromJson<Item>();
92+
Assert.That(dto1.IsFavorite, Is.True);
93+
94+
var dto0 = "{\"favorite\":0}".FromJson<Item>();
95+
Assert.That(dto0.IsFavorite, Is.False);
96+
97+
var dtoTrue = "{\"favorite\":true}".FromJson<Item>();
98+
Assert.That(dtoTrue.IsFavorite, Is.True);
99+
100+
var dtoFalse = "{\"favorite\":0}".FromJson<Item>();
101+
Assert.That(dtoFalse.IsFavorite, Is.False);
102+
}
103+
}
80104
}

0 commit comments

Comments
 (0)