From e8b1be44d165b899511294a0b1e34420862a47a1 Mon Sep 17 00:00:00 2001 From: Chris Santero Date: Sun, 18 Jan 2015 15:16:51 -0500 Subject: [PATCH] refactor GetIdFor --- JSONAPI/Json/JsonApiFormatter.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/JSONAPI/Json/JsonApiFormatter.cs b/JSONAPI/Json/JsonApiFormatter.cs index 770e74f9..e20d28f2 100644 --- a/JSONAPI/Json/JsonApiFormatter.cs +++ b/JSONAPI/Json/JsonApiFormatter.cs @@ -137,7 +137,8 @@ protected void Serialize(object value, Stream writeStream, JsonWriter writer, Js // Do the Id now... writer.WritePropertyName("id"); - writer.WriteValue(GetIdFor(value)); + var idProp = GetIdProperty(value.GetType()); + writer.WriteValue(GetValueForIdProperty(idProp, value)); PropertyInfo[] props = value.GetType().GetProperties(); // Do non-model properties first, everything else goes in "links" @@ -146,8 +147,7 @@ protected void Serialize(object value, Stream writeStream, JsonWriter writer, Js foreach (PropertyInfo prop in props) { - //FIXME: The "id" property might not be named "Id"! - if (FormatPropertyName(prop.Name) == "id") continue; // We did the Id above, don't do it twice! + if (prop == idProp) continue; if (this.CanWriteTypeAsPrimitive(prop.PropertyType)) { @@ -811,10 +811,8 @@ protected PropertyInfo GetIdProperty(Type type) return type.GetProperty("Id"); } - protected string GetIdFor(object obj) + protected string GetValueForIdProperty(PropertyInfo idprop, object obj) { - Type type = obj.GetType(); - PropertyInfo idprop = GetIdProperty(type); if (idprop != null) { if (idprop.PropertyType == typeof(string)) @@ -827,6 +825,13 @@ protected string GetIdFor(object obj) return "NOIDCOMPUTABLE!"; } + protected string GetIdFor(object obj) + { + Type type = obj.GetType(); + PropertyInfo idprop = GetIdProperty(type); + return GetValueForIdProperty(idprop, obj); + } + private void WriteIdsArrayJson(Newtonsoft.Json.JsonWriter writer, IEnumerable value, Newtonsoft.Json.JsonSerializer serializer) { IEnumerator collectionEnumerator = (value as IEnumerable).GetEnumerator();