Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eliminate spurious ToString calls during deserialization #873

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions RestSharp.Tests/JsonTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,131 @@ public void Can_Deserialize_Dictionary_with_Null()
Assert.IsNull(dictionary["Null"]);
}

[Test]
public void Does_Not_ToString_Complex_Objects_During_Deserialization()
{
string complexObjectData = SimpleJson.SerializeObject(Nested.Build(levels: 4));
JsonObject intermediateDeserializedForm = SimpleJson.DeserializeObject(complexObjectData) as JsonObject;
ToStringWatcher watcher = new ToStringWatcher(intermediateDeserializedForm);
Nested deserializedData = new JsonDeserializer().ConvertValue(typeof(Nested), watcher.Root) as Nested;

Assert.IsNotNull(deserializedData);
deserializedData.AssertStructureIsCorrect(levels: 4);
Assert.AreEqual(0, watcher.ToStringCount);
}

class ToStringWatcher
{
JsonObject _root;
int _toStringCount;

public ToStringWatcher(JsonObject rawData)
{
_root = new ToStringWatcherJsonObject(rawData, this);
}

private void CountToString()
{
_toStringCount++;
}

class ToStringWatcherJsonObject : JsonObject
{
ToStringWatcher _rootWatcher;

public ToStringWatcherJsonObject(JsonObject other, ToStringWatcher rootWatcher)
{
foreach (var item in other)
{
object value = item.Value;

if (value is JsonObject)
value = new ToStringWatcherJsonObject((JsonObject)value, rootWatcher);

base[item.Key] = value;
}

_rootWatcher = rootWatcher;
}

public override string ToString()
{
_rootWatcher.CountToString();
return base.ToString();
}
}

public JsonObject Root { get { return _root; } }
public int ToStringCount { get { return _toStringCount; } }
}

class Nested
{
public Nested First { get; set; }
public Nested Second { get; set; }
public Nested Third { get; set; }

public int Value { get; set; }

public static Nested Build(int levels)
{
int valueCounter = 0;

return Build(levels, ref valueCounter);
}

static Nested Build(int levels, ref int valueCounter)
{
Nested ret = new Nested();

if (levels == 0)
ret.Value = valueCounter++;
else
{
ret.Value = -1;

ret.First = Build(levels - 1, ref valueCounter);
ret.Second = Build(levels - 1, ref valueCounter);
ret.Third = Build(levels - 1, ref valueCounter);
}

return ret;
}

public void AssertStructureIsCorrect(int levels)
{
int valueCounter = 0;

AssertStructureIsCorrect(levels, ref valueCounter);
}

void AssertStructureIsCorrect(int levels, ref int valueCounter)
{
if (levels == 0)
{
Assert.IsNull(this.First);
Assert.IsNull(this.Second);
Assert.IsNull(this.Third);

Assert.AreEqual(valueCounter, this.Value);

valueCounter++;
}
else
{
Assert.IsNotNull(this.First);
Assert.IsNotNull(this.Second);
Assert.IsNotNull(this.Third);

Assert.AreEqual(-1, this.Value);

this.First.AssertStructureIsCorrect(levels - 1, ref valueCounter);
this.Second.AssertStructureIsCorrect(levels - 1, ref valueCounter);
this.Third.AssertStructureIsCorrect(levels - 1, ref valueCounter);
}
}
}

private static string CreateJsonWithUnderscores()
{
JsonObject doc = new JsonObject();
Expand Down
101 changes: 61 additions & 40 deletions RestSharp/Deserializers/JsonDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,26 +207,37 @@ private IList BuildList(Type type, object parent)
return list;
}

private object ConvertValue(Type type, object value)
class LazyToString
{
string stringValue = Convert.ToString(value, this.Culture);
object _value;
IFormatProvider _formatProvider;
string _convertedValue;

// check for nullable and extract underlying type
#if !WINDOWS_UWP
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
#else
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
#endif
public LazyToString(object value, IFormatProvider formatProvider)
{
// Since the type is nullable and no value is provided return null
if (string.IsNullOrEmpty(stringValue))
_value = value;
_formatProvider = formatProvider;
}

public string Value
{
get
{
return null;
}
if (_convertedValue == null)
{
_convertedValue = Convert.ToString(_value, _formatProvider);

type = type.GetGenericArguments()[0];
if (_convertedValue == null)
_convertedValue = "";
}

return _convertedValue;
}
}
}

internal object ConvertValue(Type type, object value)
{
if (type == typeof(object))
{
if (value == null)
Expand All @@ -237,35 +248,49 @@ private object ConvertValue(Type type, object value)
}

#if !WINDOWS_UWP
if (type.IsPrimitive)
{
return value.ChangeType(type, this.Culture);
}
bool typeIsGenericType = type.IsGenericType;
bool typeIsPrimitive = type.IsPrimitive;
bool typeIsEnum = type.IsEnum;
#else
var typeInfo = type.GetTypeInfo();

if (type.IsEnum)
bool typeIsGenericType = typeInfo.IsGenericType;
bool typeIsPrimitive = typeInfo.IsPrimitive;
bool typeIsEnum = typeInfo.IsEnum;
#endif

// check for nullable and extract underlying type
if (typeIsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return type.FindEnumValue(stringValue, this.Culture);
// Since the type is nullable and no value is provided return null
if ((value == null) || "".Equals(value))
{
return null;
}

return ConvertValue(type.GetGenericArguments()[0], value);
}
#else
if (type.GetTypeInfo().IsPrimitive)

if (typeIsPrimitive)
{
return value.ChangeType(type, this.Culture);
}

if (type.GetTypeInfo().IsEnum)
LazyToString stringValue = new LazyToString(value, this.Culture);

if (typeIsEnum)
{
return type.FindEnumValue(stringValue, this.Culture);
return type.FindEnumValue(stringValue.Value, this.Culture);
}
#endif

if (type == typeof(Uri))
{
return new Uri(stringValue, UriKind.RelativeOrAbsolute);
return new Uri(stringValue.Value, UriKind.RelativeOrAbsolute);
}

if (type == typeof(string))
{
return stringValue;
return stringValue.Value;
}

if (type == typeof(DateTime) || type == typeof(DateTimeOffset))
Expand All @@ -274,13 +299,13 @@ private object ConvertValue(Type type, object value)

if (this.DateFormat.HasValue())
{
dt = DateTime.ParseExact(stringValue, this.DateFormat, this.Culture,
dt = DateTime.ParseExact(stringValue.Value, this.DateFormat, this.Culture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
}
else
{
// try parsing instead
dt = stringValue.ParseJsonDate(this.Culture);
dt = stringValue.Value.ParseJsonDate(this.Culture);
}

if (type == typeof(DateTime))
Expand All @@ -300,36 +325,32 @@ private object ConvertValue(Type type, object value)
return (decimal) ((double) value);
}

if (stringValue.Contains("e"))
if (stringValue.Value.Contains("e"))
{
return decimal.Parse(stringValue, NumberStyles.Float, this.Culture);
return decimal.Parse(stringValue.Value, NumberStyles.Float, this.Culture);
}

return decimal.Parse(stringValue, this.Culture);
return decimal.Parse(stringValue.Value, this.Culture);
}
else if (type == typeof(Guid))
{
return string.IsNullOrEmpty(stringValue)
return string.IsNullOrEmpty(stringValue.Value)
? Guid.Empty
: new Guid(stringValue);
: new Guid(stringValue.Value);
}
else if (type == typeof(TimeSpan))
{
TimeSpan timeSpan;

if (TimeSpan.TryParse(stringValue, out timeSpan))
if (TimeSpan.TryParse(stringValue.Value, out timeSpan))
{
return timeSpan;
}

// This should handle ISO 8601 durations
return XmlConvert.ToTimeSpan(stringValue);
return XmlConvert.ToTimeSpan(stringValue.Value);
}
#if !WINDOWS_UWP
else if (type.IsGenericType)
#else
else if (type.GetTypeInfo().IsGenericType)
#endif
else if (typeIsGenericType)
{
Type genericTypeDef = type.GetGenericTypeDefinition();

Expand Down