Blixt
Blixt

Reputation: 50169

Using a different type for a collection when serializing with WCF

Imagine I've got a data object that makes sense in an OO model, but for serialization I want to have its fields referencing other types replaced with simply an ID, or in some cases, a simple object with a text and an ID.

Is it possible to have the serializer to handle specific fields differently, or do I have to redefine a second data object class from scratch with the simplified fields and use that?

Example:

Person
  Guid Id
  string Name
  List<Person> Siblings

What I want to be serialized:

Person
  Guid Id
  string Name
  List<Guid> Siblings

I would like to only have the one class, Person, and define the serialization behavior for my service (preferably not at a data type level, since it could be serialized as both XML or JSON).

I know about the support for references in WCF, but in this case I will be referencing other types not included elsewhere in the result set; I only want to include their ids.

Upvotes: 0

Views: 255

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

You could exclude Siblings property from serialization and add a readonly SiblingGuids:

Person
  Guid Id
  string Name
  [NonSerialized]
  List<Person> Siblings
  List<Guid> SiblingGuids // Only a getter which will expose guids

Upvotes: 1

Paul Turner
Paul Turner

Reputation: 39625

Once you change the structure of the information being transmitted, a data transfer object is probably the cleanest and simplest choice.

In fact, I would always recommend creating dedicated DTOs for WCF services, to separate the service and the data it transmits from the domain model I'm normally working against. There is the overhead of managing changes with the model and service separately, but it's much less work than having to force your domain objects into the right shape for your service and then trying to keep them there.

Upvotes: 1

Related Questions