Allow [Parameter] to control JSON Field Names.

Previously, SimpleJsonSerializer.MapClrMemberNameToJsonFieldName
special cased the name "Links" since while that was the name of the
property in the object model, in JSON "_links" was used instead.

It turns out that there was an additional problem, where GitReference
wants to expose as Repository, but the name in JSON responses is
"repo".  Instead of simply adding another special case to
MapClrMemberNameToJsonFieldName, we update the implementation of the
serializer to allow [Parameter(Key = "some_name")] to denote what name
we'd like to use for the field in the JSON object when we serialize.
This commit is contained in:
Matt G. Ellis
2014-11-17 22:52:01 -08:00
parent 808ffe6081
commit d0dcbe8fb6
3 changed files with 17 additions and 8 deletions

View File

@@ -26,11 +26,17 @@ namespace Octokit.Internal
readonly List<string> _membersWhichShouldPublishNull
= new List<string>();
protected override string MapClrMemberNameToJsonFieldName(string clrPropertyName)
protected override string MapClrMemberToJsonFieldName(MemberInfo member)
{
var rubyCased = clrPropertyName.ToRubyCase();
if (rubyCased == "links") return "_links"; // Special case for GitHub API
return rubyCased;
var memberName = member.Name;
var paramAttr = member.GetCustomAttribute<ParameterAttribute>();
if (paramAttr != null && !string.IsNullOrEmpty(paramAttr.Key))
{
memberName = paramAttr.Key;
}
return memberName.ToRubyCase();
}
internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
@@ -53,7 +59,7 @@ namespace Octokit.Internal
var attribute = propertyInfo.GetCustomAttribute<SerializeNullAttribute>();
if (attribute == null)
continue;
_membersWhichShouldPublishNull.Add(fullName + MapClrMemberNameToJsonFieldName(propertyInfo.Name));
_membersWhichShouldPublishNull.Add(fullName + MapClrMemberToJsonFieldName(propertyInfo));
}
foreach (var fieldInfo in ReflectionUtils.GetFields(type))
{
@@ -62,7 +68,7 @@ namespace Octokit.Internal
var attribute = fieldInfo.GetCustomAttribute<SerializeNullAttribute>();
if (attribute == null)
continue;
_membersWhichShouldPublishNull.Add(fullName + MapClrMemberNameToJsonFieldName(fieldInfo.Name));
_membersWhichShouldPublishNull.Add(fullName + MapClrMemberToJsonFieldName(fieldInfo));
}
return base.GetterValueFactory(type);
@@ -89,7 +95,7 @@ namespace Octokit.Internal
continue;
}
jsonObject.Add(MapClrMemberNameToJsonFieldName(getter.Key), value);
jsonObject.Add(getter.Key, value);
}
}
output = jsonObject;