How to exclude some members from being serialized to Json?

前端 未结 3 740
予麋鹿
予麋鹿 2021-01-12 07:45

I have an object that I want to serialize to Json format I\'m using:

    public string ToJson()
    {
        JavaScriptSerializer jsonSerializer = new JavaS         


        
3条回答
  •  被撕碎了的回忆
    2021-01-12 07:57

    The possible way is to declare those fields as private or internal.

    The alternative solution is to use DataContractJsonSerializer class. In this case you add DataContract attribute to your class. You can control the members you want to serialize with DataMember attribute - all members marked with it are serialized, and the others are not.

    You should rewrite your ToJson method as follows:

        public string ToJson()
        {
            DataContractJsonSerializer jsonSerializer = 
                  new DataContractJsonSerializer(typeof());
            MemoryStream ms = new MemoryStream();
            jsonSerializer.WriteObject(ms, this);
            string json = Encoding.Default.GetString(ms.ToArray());
            ms.Dispose();
            return json;
        }
    

提交回复
热议问题