Skip to content

Commit 9a1a1fd

Browse files
committed
Merge pull request #291 from petejohanson/single_list_item_support
Allow deserializing a single item into a List<T> field, for JSON that on...
2 parents 7229095 + 82f6bcd commit 9a1a1fd

File tree

2 files changed

+41
-15
lines changed

2 files changed

+41
-15
lines changed

RestSharp.Tests/JsonTests.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
using System.Diagnostics;
2020
using System.Globalization;
2121
using System.IO;
22+
using System.Linq;
2223
using Newtonsoft.Json;
2324
using Newtonsoft.Json.Converters;
2425
using Newtonsoft.Json.Linq;
@@ -70,6 +71,28 @@ public void Can_Deserialize_Simple_Generic_List_of_Simple_Types()
7071
Assert.NotEmpty(output);
7172
}
7273

74+
[Fact]
75+
public void Can_Deserialize_Simple_Generic_List_Given_Item_Without_Array ()
76+
{
77+
const string content = "{\"users\":\"johnsheehan\"}";
78+
var json = new JsonDeserializer { RootElement = "users" };
79+
80+
var output = json.Deserialize<List<string>> (new RestResponse { Content = content });
81+
82+
Assert.True (output.SequenceEqual (new[] { "johnsheehan" }));
83+
}
84+
85+
[Fact]
86+
public void Can_Deserialize_Simple_Generic_List_Given_Toplevel_Item_Without_Array ()
87+
{
88+
const string content = "\"johnsheehan\"";
89+
var json = new JsonDeserializer ();
90+
91+
var output = json.Deserialize<List<string>> (new RestResponse { Content = content });
92+
93+
Assert.True (output.SequenceEqual (new[] { "johnsheehan" }));
94+
}
95+
7396
[Fact]
7497
public void Can_Deserialize_From_Root_Element()
7598
{

RestSharp/Deserializers/JsonDeserializer.cs

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -200,22 +200,25 @@ private IList BuildList(Type type, object parent)
200200
var list = (IList)Activator.CreateInstance(type);
201201
var itemType = type.GetGenericArguments()[0];
202202

203-
foreach (var element in (IList)parent)
204-
{
205-
if (itemType.IsPrimitive)
206-
{
207-
var value = element.ToString();
208-
list.Add(value.ChangeType(itemType, Culture));
209-
}
210-
else if (itemType == typeof(string))
211-
{
212-
list.Add(element.ToString());
213-
}
214-
else
215-
{
216-
var item = CreateAndMap(itemType, element);
217-
list.Add(item);
203+
if (parent is IList) {
204+
foreach (var element in (IList)parent) {
205+
if (itemType.IsPrimitive)
206+
{
207+
var value = element.ToString ();
208+
list.Add (value.ChangeType (itemType, Culture));
209+
}
210+
else if (itemType == typeof (string))
211+
{
212+
list.Add (element.ToString ());
213+
}
214+
else
215+
{
216+
var item = CreateAndMap (itemType, element);
217+
list.Add (item);
218+
}
218219
}
220+
} else {
221+
list.Add (CreateAndMap (itemType, parent));
219222
}
220223
return list;
221224
}

0 commit comments

Comments
 (0)