HAL JSON support for Json.Net
HAL JSON support for Json.Net
Model:
public class Model
{
public uint Id { get; set; }
public string Name { get; set; }
public List<int> ItemIds { get; set; }
}
Configuration:
var config = HalJsonConfiguration("http://example.com/api"); //You can use null instead of example.com, it won't touch your links in that case
config.Configure<Model>()
.Embed(p => p.ItemIds)
.Link("self", x => "/model/" + x.Id)
.Link("all", "/model");
var serializer = new JsonSerializer{ContractResolver = new JsonNetHalJsonContactResolver(config)};
//Use serializer here
Results:
{
"_links": {
"all": {
"href": "http://example.com/api/model",
"templated": "false"
},
"self": {
"href": "http://example.com/api/model/42",
"templated": "false"
}
},
"_embedded": {
"itemIds": [
1,
2,
3
]
},
"id": 42,
"name": "One"
}
You may as well use IHaveHalJsonLinks and IHaveHalJsonEmbedded:
public class AdvancedModel: IHaveHalJsonLinks, IHaveHalJsonEmbedded
{
public IDictionary<string, Link> GetLinks()
{
return new Dictionary<string, Link> {{"self", "/something"}};
}
public IDictionary<string, Embedded> GetEmbedded()
{
return new Dictionary<string, Embedded> {{"ids", new Embedded(new[] {1, 2, 3})}};
}
}
Or attributes:
[HalJsonLink("something", "123")]
public class AttributeBasedModel
{
[HalJsonLink("self", "/mdl/{0}")]
public int Id { get; set; }
[HalJsonEmbedded("ids")]
public List<int> Ids { get; set; }
}
Or even mix them together.