【发布时间】:2017-10-06 01:11:09
【问题描述】:
我定义了这个简单的类型:
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 不是答案。提前致谢。
【问题讨论】:
-
你能提供你目前的序列化代码吗?
-
您确定这是有效的吗?价格 = 2.3 。您不需要新建结构吗?
-
@Thangadurai 隐式运算符
public static implicit operator Price(decimal d)负责处理
标签: c# json serialization deserialization