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

Commit c0046ad

Browse files
committed
Fix deserializing read-only empty collection
1 parent 967d8ed commit c0046ad

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

src/ServiceStack.Text/Common/DeserializeListWithElements.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,8 @@ public static ICollection<T> ParseGenericList(string value, Type createListType,
128128
? new List<T>()
129129
: (ICollection<T>)createListType.CreateInstance();
130130

131-
if (value == string.Empty) return to;
131+
if (value == string.Empty)
132+
return isReadOnly ? (ICollection<T>)Activator.CreateInstance(createListType, to) : to;
132133

133134
var tryToParseItemsAsPrimitiveTypes =
134135
JsConfig.TryToParsePrimitiveTypeValues && typeof(T) == typeof(object);
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System.Collections.Generic;
2+
using NUnit.Framework;
3+
using ServiceStack;
4+
using ServiceStack.Text;
5+
using System.Collections.ObjectModel;
6+
7+
namespace ServiceStack.Text.Tests.JsonTests
8+
{
9+
public class JsonEnnumerableTests
10+
{
11+
public class ModelWithReadOnlyCollection
12+
{
13+
public ReadOnlyCollection<string> Results { get; set; }
14+
}
15+
16+
[Test]
17+
public void Does_deserialize_Empty_ReadOnlyCollection()
18+
{
19+
var dto = "{\"Results\":[]}".FromJson<ModelWithReadOnlyCollection>();
20+
Assert.That(dto.Results.Count, Is.EqualTo(0));
21+
}
22+
23+
public class ModelWithList
24+
{
25+
public List<string> Results { get; set; }
26+
}
27+
28+
[Test]
29+
public void Does_deserialize_Empty_List()
30+
{
31+
var dto = "{\"Results\":[]}".FromJson<ModelWithList>();
32+
Assert.That(dto.Results.Count, Is.EqualTo(0));
33+
}
34+
}
35+
}

tests/ServiceStack.Text.Tests/ServiceStack.Text.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@
196196
<Compile Include="JsonTests\InheritAbstractTests.cs" />
197197
<Compile Include="JsonTests\InheritanceTests.cs" />
198198
<Compile Include="JsonTests\JsonDecimalTests.cs" />
199+
<Compile Include="JsonTests\JsonEnnumerableTests.cs" />
199200
<Compile Include="JsonTests\JsonEnumTests.cs" />
200201
<Compile Include="JsonTests\InvalidJsonTests.cs" />
201202
<Compile Include="JsonTests\OnDeserializationErrorTests.cs" />

0 commit comments

Comments
 (0)