Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I add [JsonIgnore] to prevent certain properties from being serialized?

Tags:

asp.net-mvc

This is a very simple Web API project. I have a data model, generated DbContext, and a controller.

When I add the [JsonIgnore] attribute to certain properties on my model classes and then later make a change to the data model, the model classes get regenerated and my [JsonIgnore] attribute is deleted. I understand why this happens and that I shouldn't be adding attributes to an auto-generated class. My question is, where should I be annotating classes with attributes, like [JsonIgnore] for use with ASP.NET Web API?

ASP.NET Web API 4, RTW

like image 934
Scott Avatar asked Aug 24 '12 13:08

Scott


People also ask

How can you prevent a property from being serialized?

How can you prevent a property from being serialized? You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable.

How do you ignore certain fields based on a serializing object to JSON?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

Which of the following attribute should be used to indicate the property must not be serialized while using JSON serializer?

We still use [JsonIgnore] attribute, adding it to the property which we do not want to be serialized. Add an alternate private property setter to the class with the same type as the original property. Then set the value to the original property in the implementation.


1 Answers

You should use view models. Basically define classes that will contain only the properties that you need to expose and then return those view models from your Web API actions. This way you don't have to worry about polluting your domain models with [JsonIgnore] attributes especially if you don't want those properties to be ignored only for certain actions. In order to simplify the mapping between your domain models and view models you may take a look at AutoMapper.

like image 106
Darin Dimitrov Avatar answered Sep 26 '22 03:09

Darin Dimitrov