如何序列化不可变结构

时间:2019-05-22 09:06:32

标签: serialization struct .net-core json.net immutability

我正在尝试使用JSon.NET序列化一个不可变的结构,但我不怎么做。序列化的结果是一个空的json {}。我更喜欢使用{{1} },而不是像JsonNET这样重的东西。

结构

BinaryFormatter

程序

[Serializable]
    public struct Settings : IEquatable<Settings> {

        private readonly (
            TimeSpan from,
            TimeSpan until,
            TimeSpan repeatInterval,
            TimeSpan popupInterval,
            string notes
        ) _value;

        [JsonIgnore]
        public TimeSpan From => _value.from;
        [JsonIgnore]
        public TimeSpan Until => _value.until;
        [JsonIgnore]
        public TimeSpan Repeat => _value.repeatInterval;
        [JsonIgnore]
        public TimeSpan PopUpInterval => _value.popupInterval;
        [JsonIgnore]
        public string Notes => _value.notes;



        public Settings(
            TimeSpan from,
            TimeSpan until,
            TimeSpan repeatInterval,
            TimeSpan popUpInterval,
            string notes
        ) => _value = (
            from,
            until,
            repeatInterval,
            popUpInterval,
            notes
        );

        public bool Equals(Settings other) => _value == other._value;
        public override bool Equals(object obj) => obj is Settings other && this.Equals(other);
        public override int GetHashCode() => _value.GetHashCode();
        public override string ToString() => _value.ToString();



        public static bool operator ==(Settings a, Settings b) => a.Equals(b);
        public static bool operator !=(Settings a, Settings b) => !(a == b);
    }

1 个答案:

答案 0 :(得分:1)

对于序列化,JsonIgnore属性需要从目标属性中删除。对于反序列化,将在反序列化期间使用的构造函数需要标记为JsonConstruct属性。可选地,需要通过JsonProperty属性将序列化名称(属性)与反序列化名称(此处为构造函数参数)进行协调。

    public TimeSpan From => _value.from;

    public TimeSpan Until => _value.until;

    public TimeSpan Repeat => _value.repeatInterval;

    public TimeSpan PopUpInterval => _value.popupInterval;

    public string Notes => _value.notes;

    [JsonConstructor] //choose a constructor for deserialization
    public Settings(
        TimeSpan from,
        TimeSpan until,
        [JsonProperty("Repeat")]TimeSpan repeatInterval, //same name used for serialization
        TimeSpan popUpInterval,
        string notes
    ) => _value = (
        from,
        until,
        repeatInterval,
        popUpInterval,
        notes
    );