diff --git a/JSONAPI.Tests/Data/LinkTemplateTest.json b/JSONAPI.Tests/Data/LinkTemplateTest.json new file mode 100644 index 00000000..6d351b09 --- /dev/null +++ b/JSONAPI.Tests/Data/LinkTemplateTest.json @@ -0,0 +1,11 @@ +{ + "posts": { + "id": "2", + "title": "How to fry an egg", + "links": { + "author": { + "href": "/users/5" + } + } + } +} \ No newline at end of file diff --git a/JSONAPI.Tests/JSONAPI.Tests.csproj b/JSONAPI.Tests/JSONAPI.Tests.csproj index b6265c16..1aa796f1 100644 --- a/JSONAPI.Tests/JSONAPI.Tests.csproj +++ b/JSONAPI.Tests/JSONAPI.Tests.csproj @@ -79,6 +79,7 @@ + @@ -98,6 +99,9 @@ Always + + Always + Always diff --git a/JSONAPI.Tests/Json/LinkTemplateTests.cs b/JSONAPI.Tests/Json/LinkTemplateTests.cs new file mode 100644 index 00000000..c74c4943 --- /dev/null +++ b/JSONAPI.Tests/Json/LinkTemplateTests.cs @@ -0,0 +1,67 @@ +using JSONAPI.Attributes; +using JSONAPI.Json; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics; +using System.IO; +using System.Text; + +namespace JSONAPI.Tests.Json +{ + [TestClass] + public class LinkTemplateTests + { + private class Post + { + public string Id { get; set; } + + public string Title { get; set; } + + [SerializeAs(SerializeAsOptions.Link)] + [LinkTemplate("/users/{0}")] + public virtual User Author { get; set; } + } + + private class User + { + public string Id { get; set; } + + public string Name { get; set; } + } + + private Post ThePost { get; set; } + + [TestInitialize] + public void SetupModels() + { + ThePost = new Post + { + Id = "2", + Title = "How to fry an egg", + Author = new User + { + Id = "5", + Name = "Bob" + } + }; + } + + [TestMethod] + [DeploymentItem(@"Data\LinkTemplateTest.json")] + public void GetResourceWithLinkTemplateRelationship() + { + var formatter = new JsonApiFormatter + { + PluralizationService = new JSONAPI.Core.PluralizationService() + }; + var stream = new MemoryStream(); + + formatter.WriteToStreamAsync(typeof(Post), ThePost, stream, null, null); + + // Assert + var expected = JsonHelpers.MinifyJson(File.ReadAllText("LinkTemplateTest.json")); + var output = Encoding.ASCII.GetString(stream.ToArray()); + Trace.WriteLine(output); + Assert.AreEqual(output.Trim(), expected); + } + } +} diff --git a/JSONAPI/Json/JsonApiFormatter.cs b/JSONAPI/Json/JsonApiFormatter.cs index ea1cf51a..63a47e01 100644 --- a/JSONAPI/Json/JsonApiFormatter.cs +++ b/JSONAPI/Json/JsonApiFormatter.cs @@ -296,7 +296,10 @@ protected void Serialize(object value, Stream writeStream, JsonWriter writer, Js string link = String.Format(lt, objId, value.GetType().GetProperty("Id").GetValue(value, null)); //writer.WritePropertyName(ContractResolver.FormatPropertyName(prop.Name)); + writer.WriteStartObject(); + writer.WritePropertyName("href"); writer.WriteValue(link); + writer.WriteEndObject(); break; case SerializeAsOptions.Embedded: // Not really supported by Ember Data yet, incidentally...but easy to implement here.