Skip to content

Commit

Permalink
Ignore underscores when parsing enums under deserialization.
Browse files Browse the repository at this point in the history
  • Loading branch information
janovesk committed Feb 25, 2015
1 parent 015ecb9 commit 46e5721
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 8 additions & 0 deletions Octokit.Tests/SimpleJsonSerializerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,16 @@ public void HandlesBase64EncodedStrings()
}
}


public class TheDeserializeMethod
{
[Fact]
public void DeserializesEventInfosWithUnderscoresInName()
{
const string json = "{\"event\":\"head_ref_deleted\"}";
new SimpleJsonSerializer().Deserialize<EventInfo>(json);
}

[Fact]
public void UnderstandsRubyCasing()
{
Expand Down
13 changes: 12 additions & 1 deletion Octokit/Http/SimpleJsonSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,11 @@ public override object DeserializeObject(object value, Type type)
var stringValue = value as string;
if (stringValue != null)
{
stringValue = stringValue.Replace("-", "");
if (ReflectionUtils.GetTypeInfo(type).IsEnum)
{
// remove '-' from values coming in to be able to enum utf-8
stringValue = stringValue.Replace("-", "");
stringValue = RemoveHyphenAndUnderscore(stringValue);
return Enum.Parse(type, stringValue, ignoreCase: true);
}

Expand All @@ -99,6 +100,7 @@ public override object DeserializeObject(object value, Type type)
var underlyingType = Nullable.GetUnderlyingType(type);
if (ReflectionUtils.GetTypeInfo(underlyingType).IsEnum)
{
stringValue = RemoveHyphenAndUnderscore(stringValue);
return Enum.Parse(underlyingType, stringValue, ignoreCase: true);
}
}
Expand All @@ -118,6 +120,15 @@ public override object DeserializeObject(object value, Type type)
return base.DeserializeObject(value, type);
}

static string RemoveHyphenAndUnderscore(string stringValue)
{
// remove '-' from values coming in to be able to enum utf-8
stringValue = stringValue.Replace("-", "");
// remove '-' from values coming in to be able to enum EventInfoState names with underscores in them. Like "head_ref_deleted"
stringValue = stringValue.Replace("_", "");
return stringValue;
}

internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
{
return type.GetPropertiesAndFields()
Expand Down

0 comments on commit 46e5721

Please sign in to comment.