2

I am using the MVC ApiController to create an API for my website.

I have a base class ThinDevice that contains a subset of information for a Device. In my API I only want to serialize the properties belonging to ThinDevice but, despite me casting, and using ThinDevice as the return type when I serialize a Device it always serializes the entire object

[HttpGet]
public ThinDevice Get(string id)
{
    // This returns Device
    var device = this.dataService.GetDevice(id);

    if (device != null)
    {
        // I only want to serialize properties in ThinDevice
        return device as ThinDevice;
    }
}
3
  • 1
    Isn't that expected? Commented Jun 8, 2015 at 10:50
  • I would expect that it would serialize based on my return type. Even if my expectation is wrong I'd like to know how to do it :) Commented Jun 8, 2015 at 10:55
  • may be you change the return type of dataService.GetDevice(id). because derived types might contain values for some base class properties, may be to make the object graph complete , the serialization is considering the derived type. Commented Jun 8, 2015 at 11:01

1 Answer 1

2

This behaviour is expected. You can check this question for details.

Option 1: I would suggest to create an instance of ThinDevice manually, or if this class is abstract, then itroduce some separate model for the response.

Sample:

public class ThinDevice
{
    public string A { get; set; }
}

public class Device1 : ThinDevice
{
    public string B { get; set; }
}

[HttpGet]
public ThinDevice Get()
{
    return GetDeviceResponse(new Device1 { A = "A", B = "B" });
}

private ThinDevice GetDeviceResponse<T>(T device) where T : ThinDevice
{
    return new ThinDevice
    {
        A = device.A
    };
}

This code is not very nice (especially if you have complex object structure).

Option 2: You can implement custom JSON and XML serialization that will include only data that you want, but this can be difficult.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.