问题描述:

Reduced down to its simplest form, I have a class that inherits from another

public class BaseClass

{

protected int _property1;

public virtual int Property1

{

get

{

return _property1;

}

set

{

_property1 = value;

}

}

public int Property2 { get; set; }

}

public class InheritedClass : BaseClass

{

public override int Property1

{

set

{

_property1 = value + 1;

}

}

public int Property3 { get; set; }

}

And a WebAPI controller

public class TestController : ApiController

{

// GET api/test/5

public InheritedClass Get(int id)

{

return new InheritedClass

{

Property1 = id + 1,

Property2 = id,

Property3 = id - 1

};

}

}

If I request XML from the controller, with GET api/test/1, I get the data I expect

<InheritedClass>

<Property1>3</Property1>

<Property2>1</Property2>

<Property3>0</Property3>

</InheritedClass>

but if I request JSON, it omits the inherited property.

{"Property3":0,"Property2":1}

What I want is

{"Property1":3, "Property3":0, "Property2":1}

I can fix it by changing InheritedClass to

public class InheritedClass : BaseClass

{

public override int Property1

{

get

{

return _property1;

}

set

{

_property1 = value + 1;

}

}

...

But I don't really want to - that seems rather WET. What gives? Is there a setting on the JSONFormatter I'm missing?

网友答案:

You can configure the Json serialization by using the Formatters.JsonFormatter of your HttpConfiguration object.

By configuring the DefaultContractResolver to search for public, non public and instance properties explicitly, you can fix the behavior you are seeing.

You can do this by adding the following code to your WebApiConfig.cs file in the App_Start folder:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new DefaultContractResolver
     {
         DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
     };
相关阅读:
Top