How to exclude property from Json Serialization

后端 未结 7 1540
粉色の甜心
粉色の甜心 2020-11-22 13:22

I have a DTO class which I Serialize

Json.Serialize(MyClass)

How can I exclude a public property of it?

(It has to

7条回答
  •  一整个雨季
    2020-11-22 13:34

    If you are using System.Web.Script.Serialization in the .NET framework you can put a ScriptIgnore attribute on the members that shouldn't be serialized. See the example taken from here:

    Consider the following (simplified) case:

    public class User {
        public int Id { get; set; }
        public string Name { get; set; }
        [ScriptIgnore]
        public bool IsComplete
        {
            get { return Id > 0 && !string.IsNullOrEmpty(Name); }
        } 
    } 
    

    In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:

    { Id: 3, Name: 'Test User' }
    

    PS. Don't forget to add a reference to "System.Web.Extensions" for this to work

提交回复
热议问题