Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering attributes in ASP.NET WebApi response models inheriting href and id from a base class

I have an ASP.NET Web Api 2 project with several response models. In an attempt to create a smaller payload I am offering the user the option to collapse entities to just a id and a href link, which I would like to generate automatically. I would like all my main resource response models to inherit from a base response model that has just the href and id. If I have a resource Foo, this looks something like this:

public class ResourceResponseModel
{
    public string Href { get; private set; }

    public string Id { get; private set; }

    protected ResourceResponseModel(string id)
    {
        Id = id;
    }
}

public class FooModel : ResourceResponseModel
{
    public string Name { get; private set; }

    private ExampleModel (string id, string name)
        : base(id)
    {
        Name = name;
    }

    internal static FooModel From(Foo foo)
    {
        return new FooModel(
            foo.Id,
            foo.Name
        );
    }
}

When my controller is called, this model is serialized with Microsoft.AspNet.Mvc.Json(object data)

This seems to work great, except when I look at the response I end up with, it puts the base class attributes at the end:

{
    "name": "Foo 1",
    "href": "api/abcdefg",
    "id": "abcdefg"
}

Is there an easy way to get the base attributes to appear before the resource attributes?

like image 686
08Dc91wk Avatar asked Mar 02 '16 09:03

08Dc91wk


1 Answers

You can solve this by setting the JsonProperty attribute on you properties and pass in Order.

public class ResourceResponseModel
{
    [JsonProperty(Order = -2)]
    public string Href { get; private set; }

    [JsonProperty(Order = -2)]
    public string Id { get; private set; }

    protected ResourceResponseModel(string id)
    {
        Id = id;
    }
}

Order seems to default to zero and then get sorted from low to high when serialized. Documentation can be found here.

like image 164
Simon Karlsson Avatar answered Sep 28 '22 16:09

Simon Karlsson