问题
I have an MVC 4 Web API. Usually I want responses to return all properties, but there is one place I only want to return only non-null values. I can setup either behavior by setting the JsonSerializerSettings of the Formatters.JsonFormatter.SerializerSettings.NullValueHandling of the GlobalConfiguration.Configuration instance in the global file but I want to use both depending on the response. Is there an easy way to configure the request scope from within an API controller action?
回答1:
By changing your controller action to return HttpResponseMessage you can get more control over how your content is returned for a particular action. e.g.
public HttpResponseMessage Get() {
var foo = new Foo();
var objectContent = new ObjectContent<Foo>(foo, new JsonFormatter()
{SerializerSettings.NullValueHandling = ???})
return new HttpResponseMessage() {Content = objectContent};
}
回答2:
this would probably be easier to do on the client side with a dynamic language like javascript.
var keys = Object.keys(json);
for(var i = 0; i < keys.length; i++) {
var propertyName = keys[i];
if(json[propertyName] === undefined || v[propertyName] === null) {
json.remove(propertyName);
}
}
return json;
来源:https://stackoverflow.com/questions/13652555/set-jsonserializersettings-per-response