我定義這個簡單類型:用戶定義的結構和默認(德)序列化
public struct Price : IComparer<Price>, IEquatable<Price> {
private readonly decimal _value;
public Price(Price value) {
_value = value._value;
}
public Price(decimal value) {
_value = value;
}
public int Compare(Price x, Price y) {
return x._value.CompareTo(y._value);
}
public int Compare(Price x, decimal y) {
return x._value.CompareTo(y);
}
public int Compare(decimal x, Price y) {
return x.CompareTo(y._value);
}
public bool Equals(Price other) {
return _value.Equals(other._value);
}
public override bool Equals(object obj) {
if (ReferenceEquals(null, obj))
return false;
return obj is Price && Equals((Price)obj);
}
public override int GetHashCode() {
return _value.GetHashCode();
}
public static implicit operator decimal(Price p) {
return p._value;
}
public static implicit operator Price(decimal d) {
return new Price(d);
}
}
當我反序列化JSON給來Price
它工作得很好。但是當我試圖序列化時,它會返回一個空的{ }
。我的意思是,假設有這種模式:
public class Product {
public string Name { get; set; }
public Price Price { get; set; }
}
deserializng一個JSON這樣的:
{ "Name": "Some name", "Price": 2.3 }
給了我正確的對象。但是序列化這個示例:
var p = new Product { Name = "Some name", Price = 2.3 }
創建該JSON:
{ "Name": "Some name", "Price": { } }
那麼,如何我能做告訴串行器庫(例如Json.NET和吉爾)如何序列化我的自定義類型是什麼?
UPDATE:
樣品序列化代碼,使用Json.NET
var s = JsonConvert.SerializeObject(p);
UPDATE2: 我不希望依賴於Json.NET或任何其他第三方庫。因此,在Json.NET中使用JsonConverter
並不是答案。提前致謝。
你能提供你當前的序列化代碼嗎? –
您確定這是有效的嗎?價格= 2.3。你不需要新建結構? – Thangadurai
@Thangadurai隱式運算符'公共靜態隱式運算符價格(十進制d)'照顧那 –