我有一个简单的类型定义:
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; }
}
反序列化这样的 JSON:
{ "Name": "Some name", "Price": 2.3 }
给我正确的对象。但是对于这个示例进行序列化:
var p = new Product { Name = "Some name", Price = 2.3 }
创建这个JSON:
{ "Name": "Some name", "Price": { } }
那么,我应该如何告诉序列化库(例如Json.NET和Jil),如何序列化我的自定义类型?以下是示例序列化代码,使用的是Json.NET。
var s = JsonConvert.SerializeObject(p);
更新2:
我不希望依赖于Json.NET或任何其他第三方库。因此,在Json.NET中使用JsonConverter
不是答案。提前感谢。
public static implicit operator Price(decimal d)
负责处理此事。 - sm_