I am new to WCF and am looking for some advice on a particular problem. I am using Enitity Framework and am wanting to return my entities as JSON through WCF. However I am only wanting to return certain information in certain circumstances. For example in one method I might want to return a users username along with their userid, in another instance I want to return a users username, userid and telephone number. Initially I thought maybe I could return an anonymous type such as
var obj = new { username = user.UserName, userid = user.UserId };
But after researching I found out that was not a good idea. I then thought of returning a Dictionary of key values, the problem with that approach is the JSON that is returned:
{"key":"username","Value":"Andrew"}
I am after something along开发者_如何学运维 the lines of
{"username":"Andrew"}
I have also though of making my own types. Is there a way to exclude properties? i.e. If my type has a property Telephone will I be able to exclude it in certain circumstances?
Any help / suggestions much appreciated
I know in DataContractSerializer, you can use EmitDefaultValue, for example, you can have a contract named UserInfo
[DataContract]
public class UserInfo
{
[DataMember]
public string UserID { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember(EmitDefaultValue=false)]
public int Age { get; set; }
[DataMember(EmitDefaultValue=false)]
public DateTime Time { get; set; }
}
I don't know whether EmitDefaultValue is supported by the JSON serializer, can you try it by yourself?
精彩评论