How to exclude property from Json Serialization

后端 未结 7 1547
粉色の甜心
粉色の甜心 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:30

    You can also use the [NonSerialized] attribute

    [Serializable]
    public struct MySerializableStruct
    {
        [NonSerialized]
        public string hiddenField;
        public string normalField;
    }
    

    From the MS docs:

    Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.


    If you're using Unity for example (this isn't only for Unity) then this works with UnityEngine.JsonUtility

    using UnityEngine;
    
    MySerializableStruct mss = new MySerializableStruct 
    { 
        hiddenField = "foo", 
        normalField = "bar" 
    };
    Debug.Log(JsonUtility.ToJson(mss)); // result: {"normalField":"bar"}
    

提交回复
热议问题