我正在尝试使用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);
}
答案 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
);