Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: adding virtual object serialization method to entities #642

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions ShopifySharp/Entities/ShopifyObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,41 @@ public abstract class ShopifyObject

[JsonProperty("admin_graphql_api_id")]
public string AdminGraphQLAPIId { get; set; }

/// <summary>
/// Converts the object to an IDictionary<string, object> for eventual serialization to JSON. Can be overridden for fine-grained control of the object's serialization.
/// </summary>
public virtual IDictionary<string, object> ToJsonDictionary()
{
IDictionary<string, object> output = new Dictionary<string, object>();

// Inspiration for this code from https://github.com/jaymedavis/stripe.net
foreach (PropertyInfo property in obj.GetType().GetAllDeclaredProperties())
{
object value = property.GetValue(obj, null);
string propName = property.Name;
if (value == null) continue;

if (property.CustomAttributes.Any(x => x.AttributeType == typeof(JsonPropertyAttribute)))
{
// Get the JsonPropertyAttribute for this property, which will give us its JSON name
JsonPropertyAttribute attribute = property
.GetCustomAttributes(typeof(JsonPropertyAttribute), false)
.Cast<JsonPropertyAttribute>()
.FirstOrDefault();

propName = attribute != null ? attribute.PropertyName : property.Name;
}

if (value.GetType().GetTypeInfo().IsEnum)
{
value = ((Enum)value).ToSerializedString();
}

output.Add(propName, value);
}

return output;
}
}
}
45 changes: 0 additions & 45 deletions ShopifySharp/Extensions/ObjectExtensions.cs

This file was deleted.