NonSerialized attributes

Oct 12, 2010 at 8:32 PM

Any way to get the serializer to ignore members tagged with the NonSerialized attribute?  I have generated code that I can't figure out another way to exclude a couple fields I don't want serialized.

Oct 12, 2010 at 11:35 PM

Put a [JsonObject(MemberSerialization = MemberSerialization.OptIn)] attribute on your class.  "OptIn" means Json.NET will only serialize the fields that have a [JsonProperty] attribute on them.  Or, you can use "OptOut", and put a [JsonIgnore] attribute on the properties you want to exclude.

Oct 13, 2010 at 12:16 AM

I can't really make changes to the classes because they're generated.  Anything I do will be wiped out next time I have to run the code generator.  Sadly, it's not flexible about adding attributes, so there's no options there.

Oct 13, 2010 at 12:35 AM

You can't modify the code generation piece to include the attributes?

Oct 13, 2010 at 2:00 AM

If you can't modify the code generation piece directly, you still have lots of options.  You could:

  • Modify the classes through some other automated process that runs after the initial code generation.
  • Create DTO classes that contain only the data you want to serialize.  Use AutoMapper to easily get DTOs from your regular objects.  Just serialize your DTOs and pass them around. (My vote)
  • Create anonymous objects from your regular objects, including only the properties you want, and serialize the anonymous objects.

 

Coordinator
Oct 13, 2010 at 2:04 AM

Inherit from DefaultContractResolver and override create properties to ignore properties that have the NonSerialized attribute.