views:

17

answers:

1

Hi all, I have a some classes which I need to serialize in two different ways: first- "basic" fields, and the second- some other fields. e.g. a User class which I sometimes need to serialize just the "first name" and "last name" fields, and sometimes I need to serialize the "id" and "email" fields as well.

The best way I found to do this so far is mark the basic fields with the [DataMember] attribute, and let .NET do the serializing for me, and for the rest mark them with a customize attribute and do the serialization myself. This solution proved to be very costly: I first sirialize the basic attributes (as mentioned, .NET does that for me) Then I get the property names of the fields marked with the custom attribute (using reflection namespace), Then I try to get the those fields and their values from the object, and add their serialization to the basic serialization (not very successfully so far).....

Question is: Is there a better way? preferbly by which .NET will do the rest of the work for me, and if not, at least one by which I don't need to go through all the object's fields, find the relevant ones and serialize them myself..

Thank you all..

+1  A: 

Oren,

Are you having to run these operations 1000x or more per minute? If not, all but the clumsiest of solutions will not be too costly. For exmample, if you need to do it like this, working from 2 objects is probably just fine. if you haven't actually run real timing comparisons, there's a huge chance you're wrong about what's expensive and what isn't.

But if you want to do it like this anyway, here is a solution that will only take 1% more time.

  • have an object, e.g., Core, for the subset, and Full for the whole thing
  • in the constructor of Full, instantiate a private instance of Core (composition pattern sort of). This has insignificant overhead.
  • Full will not have private member variables for the Core members. Full's setters and getters of the core data will refer to the private instance of Core. So no overhead.
  • Now you have 2 objects to serialize.
FastAl
Great answer!Although we eventually decided to go in a different way (have a customized object for each method, because of overlaps between fields and the fact the some fields should be added to even "Full" objects).But still, liked your answer (-:
Oren A
thanks for accepting it!
FastAl