Skip to content

Commit e8b1be4

Browse files
author
Chris Santero
committed
refactor GetIdFor
1 parent 10c7537 commit e8b1be4

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
@@ -137,7 +137,8 @@ protected void Serialize(object value, Stream writeStream, JsonWriter writer, Js
137137

138138
// Do the Id now...
139139
writer.WritePropertyName("id");
140-
writer.WriteValue(GetIdFor(value));
140+
var idProp = GetIdProperty(value.GetType());
141+
writer.WriteValue(GetValueForIdProperty(idProp, value));
141142

142143
PropertyInfo[] props = value.GetType().GetProperties();
143144
// Do non-model properties first, everything else goes in "links"
@@ -146,8 +147,7 @@ protected void Serialize(object value, Stream writeStream, JsonWriter writer, Js
146147

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

152152
if (this.CanWriteTypeAsPrimitive(prop.PropertyType))
153153
{
@@ -811,10 +811,8 @@ protected PropertyInfo GetIdProperty(Type type)
811811
return type.GetProperty("Id");
812812
}
813813

814-
protected string GetIdFor(object obj)
814+
protected string GetValueForIdProperty(PropertyInfo idprop, object obj)
815815
{
816-
Type type = obj.GetType();
817-
PropertyInfo idprop = GetIdProperty(type);
818816
if (idprop != null)
819817
{
820818
if (idprop.PropertyType == typeof(string))
@@ -827,6 +825,13 @@ protected string GetIdFor(object obj)
827825
return "NOIDCOMPUTABLE!";
828826
}
829827

828+
protected string GetIdFor(object obj)
829+
{
830+
Type type = obj.GetType();
831+
PropertyInfo idprop = GetIdProperty(type);
832+
return GetValueForIdProperty(idprop, obj);
833+
}
834+
830835
private void WriteIdsArrayJson(Newtonsoft.Json.JsonWriter writer, IEnumerable<object> value, Newtonsoft.Json.JsonSerializer serializer)
831836
{
832837
IEnumerator<Object> collectionEnumerator = (value as IEnumerable<object>).GetEnumerator();

0 commit comments

Comments
 (0)