Skip to content

Commit d4c283d

Browse files
committed
Merge pull request #12 from csantero/refactor-getidfor
refactor GetIdFor
2 parents 9259ae9 + e8b1be4 commit d4c283d

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

JSONAPI/Json/JsonApiFormatter.cs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,8 @@ protected void Serialize(object value, Stream writeStream, JsonWriter writer, Js
152152

153153
// Do the Id now...
154154
writer.WritePropertyName("id");
155-
writer.WriteValue(GetIdFor(value));
155+
var idProp = GetIdProperty(value.GetType());
156+
writer.WriteValue(GetValueForIdProperty(idProp, value));
156157

157158
PropertyInfo[] props = value.GetType().GetProperties();
158159
// Do non-model properties first, everything else goes in "links"
@@ -161,8 +162,7 @@ protected void Serialize(object value, Stream writeStream, JsonWriter writer, Js
161162

162163
foreach (PropertyInfo prop in props)
163164
{
164-
//FIXME: The "id" property might not be named "Id"!
165-
if (FormatPropertyName(prop.Name) == "id") continue; // We did the Id above, don't do it twice!
165+
if (prop == idProp) continue;
166166

167167
if (this.CanWriteTypeAsPrimitive(prop.PropertyType))
168168
{
@@ -826,10 +826,8 @@ protected PropertyInfo GetIdProperty(Type type)
826826
return type.GetProperty("Id");
827827
}
828828

829-
protected string GetIdFor(object obj)
829+
protected string GetValueForIdProperty(PropertyInfo idprop, object obj)
830830
{
831-
Type type = obj.GetType();
832-
PropertyInfo idprop = GetIdProperty(type);
833831
if (idprop != null)
834832
{
835833
if (idprop.PropertyType == typeof(string))
@@ -842,6 +840,13 @@ protected string GetIdFor(object obj)
842840
return "NOIDCOMPUTABLE!";
843841
}
844842

843+
protected string GetIdFor(object obj)
844+
{
845+
Type type = obj.GetType();
846+
PropertyInfo idprop = GetIdProperty(type);
847+
return GetValueForIdProperty(idprop, obj);
848+
}
849+
845850
private void WriteIdsArrayJson(Newtonsoft.Json.JsonWriter writer, IEnumerable<object> value, Newtonsoft.Json.JsonSerializer serializer)
846851
{
847852
IEnumerator<Object> collectionEnumerator = (value as IEnumerable<object>).GetEnumerator();

0 commit comments

Comments
 (0)