Skip to content

Commit 708adc5

Browse files
committed
JsonDeserializer now can deserialize objects JsonArray and JsonObject when their target type is specified as "System.Object" instead of a more specific type.
* The side effect of this is that now you can recursively deserialize a JSON object that has mixed value types by specifying Dictionary<string, object> as the deserialization target.
1 parent 18826dd commit 708adc5

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

RestSharp.Tests/JsonTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,20 @@ public void Can_Deserialize_From_Root_Element()
125125
Assert.Equal("John Sheehan", output.DisplayName);
126126
}
127127

128+
[Fact]
129+
public void Can_Deserialize_To_Dictionary_String_Object() {
130+
var doc = File.ReadAllText(Path.Combine("SampleData", "jsondictionary.txt"));
131+
132+
var json = new JsonDeserializer();
133+
134+
var output = json.Deserialize<Dictionary<string, object>>(new RestResponse() { Content = doc });
135+
136+
Assert.Equal(output.Keys.Count, 3);
137+
138+
var firstKeysVal = output.FirstOrDefault().Value;
139+
Assert.IsAssignableFrom<System.Collections.IDictionary>(firstKeysVal);
140+
}
141+
128142
[Fact]
129143
public void Can_Deserialize_Generic_Members()
130144
{

RestSharp/Deserializers/JsonDeserializer.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,17 @@ private object ConvertValue(Type type, object value)
267267
return CreateAndMap(type, value);
268268
}
269269
}
270-
else
270+
else if (type.IsSubclassOfRawGeneric(typeof(List<>)))
271+
{
272+
// handles classes that derive from List<T>
273+
return BuildList(type, value);
274+
}
275+
else if (type == typeof(JsonObject))
276+
{
277+
// simplify JsonObject into a Dictionary<string, object>
278+
return BuildDictionary(typeof(Dictionary<string, object>), value);
279+
}
280+
else
271281
{
272282
// nested property classes
273283
return CreateAndMap(type, value);

0 commit comments

Comments
 (0)