Set JsonSerializerSettings Per Response?

旧街凉风 提交于 2020-01-17 08:26:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!