views:

30

answers:

2

I have this Class:

public class User
{
    public string id{ get; set; }
    public string name{ get; set; }
    public string password { get; set; }
    public string email { get; set; }
    public bool is_broker { get; set; }
    public string branch_id { get; set; }
    public string created_at{get; set;}
    public string updated_at{get; set;}
    public UserGroup UserGroup {get;set;}
    public UserAddress UserAddress { get; set; }
    public List<UserContact> UserContact {get; set;}

    public User()
    {
        UserGroup = new UserGroup();
        UserAddress = new UserAddress();
        UserContact = new List<UserContact>();
    }
}

I like to Serealize Only properties , how i block serealization of UserGroup, UserAdress, asn UserContact???

This is my Serealization function:

    public static string Serealize<T>(T obj)
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        return Encoding.UTF8.GetString(ms.ToArray(), 0,(int)ms.Length);
    }
+1  A: 

Since you are using the DataContractJsonSerializer you will want to do something like this:

[DataContract]
public class User
{
    [DataMember] public string id{ get; set; }
    [DataMember] public string name{ get; set; }
    [DataMember] public string password { get; set; }
    [DataMember] public string email { get; set; }
    [DataMember] public bool is_broker { get; set; }
    [DataMember] public string branch_id { get; set; }
    [DataMember] public string created_at{get; set;}
    [DataMember] public string updated_at{get; set;}
    public UserGroup UserGroup {get;set;}
    public UserAddress UserAddress { get; set; }
    public List<UserContact> UserContact {get; set;}

    public User()
    {
        UserGroup = new UserGroup();
        UserAddress = new UserAddress();
        UserContact = new List<UserContact>();
    }
}
Andrew Hare
add my serealizatoin function!!
CrazyJoe
thank you man!! its work but i have more problems, i have to set [DataMember] to Deserealize and not set [DataMember] to Serealize!!Any trick to do this???
CrazyJoe
+1  A: 

Depending on how have implemented the serialization, you want to add the NonSerializedAttribute to the fields you don't want serialized:

http://msdn.microsoft.com/en-us/library/system.nonserializedattribute(VS.71).aspx

so for example:

  [NonSerialized()]
 public UserGroup UserGroup {get;set;}

Here is another link about the JSON serialization and how it is implemented:

http://forums.asp.net/p/1400518/3039466.aspx

Kevin