Anand
Anand

Reputation: 4551

Can I tell the WCF WebAPI serializer to ignore nested class objects?

I am using WCF WebAPI to write REST services using WCF. I am returning my POCO classes as json/xml objects from my service. Most of my POCO classes contain ICollections as they are part of EF4.1 Code First, hence I get error :

Cannot serialize member of type ... System.Collections.Generic.ICollection ... because it is of type - because it is an interface

To avoid that XMLIgnore and ScriptIgnore is suggested. And there are some problems in custom serialization of JSON in WCF.

Just thought someone might have come across a similar problem and have a better solution or way to configure serialization classes, otherwise I will have to decorate each such attribute with XMLIgnore, etc.

Upvotes: 4

Views: 1710

Answers (4)

Anand
Anand

Reputation: 4551

I found that in WCF WebAPI [ScriptIgnore] or [JsonIgnore] are not working and have no effect, so I'm going back to ASP.NET MVC for json-related REST APIs.

Update[24-Jul-2012] This answer is old, and Microsfot WebAPI has come a long way since, please check before relying on this answer.

Upvotes: 0

SeriousM
SeriousM

Reputation: 3521

Thats right Sandro, [IgnoreDataMember] and [XmlIgnore] is needed.

A little bit more explaination: [IgnoreDataMember] is needed to exclude the field in json serialization, [XmlIgnore] is needed to exclude the field in xml serialization.

Upvotes: 1

Sandro Pedrocchi
Sandro Pedrocchi

Reputation: 21

You have to add [XmlIgnore] and [IgnoreDataMember]. Then the property will be ignored for xml and json response.

Upvotes: 2

misaxi
misaxi

Reputation: 566

More often than not you probably would use DTOs or (view models in ASP.NET MVC) to decouple from your domain model. And you can use AutoMapper to minimize your code converting between domain models and DTOs.

Upvotes: 3

Related Questions