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

#169 Deserialize kebab-case #176

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
16 changes: 3 additions & 13 deletions Saule/Serialization/JsonApiContractResolver.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Serialization;

namespace Saule.Serialization
{
internal class JsonApiContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
protected override string ResolvePropertyName(string propertyName)
{
var properties = base.CreateProperties(type, memberSerialization);

foreach (var property in properties)
{
property.PropertyName = property.PropertyName.ToDashed();
}

return properties;
return propertyName.ToDashed();
}
}
}
11 changes: 8 additions & 3 deletions Saule/Serialization/ResourceDeserializer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Saule.Serialization
Expand All @@ -23,7 +24,11 @@ public ResourceDeserializer(JToken @object, Type target)
public object Deserialize()
{
ValidateTopLevel(_object);
return ToFlatStructure(_object)?.ToObject(_target);
return ToFlatStructure(_object)?.ToObject(_target, new JsonSerializer()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new JsonApiContractResolver()
});
}

private static void ValidateTopLevel(JToken content)
Expand Down Expand Up @@ -100,13 +105,13 @@ private JToken SingleToFlatStructure(JObject child)
foreach (var attr in child["attributes"] ?? new JArray())
{
var prop = attr as JProperty;
result.Add(prop?.Name.ToPascalCase(), prop?.Value);
result.Add(prop?.Name, prop?.Value);
}

foreach (var rel in child["relationships"] ?? new JArray())
{
var prop = rel as JProperty;
result.Add(prop?.Name.ToPascalCase(), ToFlatStructure(prop?.Value));
result.Add(prop?.Name, ToFlatStructure(prop?.Value));
}

return result;
Expand Down