使用Json.Net 5.0.5
我想序列化这个类
[JsonObject(MemberSerialization.OptIn)]
public class RingPoint
{
public double X { get; set; }
public double Y { get; set; }
public RingPoint(double x, double y)
{
X = x;
Y = y;
}
[JsonProperty(Required = Required.Always)]
public double[] Location { get { return new[] { X, Y }; } }
public bool Equals(RingPoint obj)
{
return obj != null && obj.X == X && obj.Y == Y;
}
}
到这个json格式
{"rings":[[[0.0,0.0],[1.0,0.0],[2.0,0.0],[0.0,0.0]]]}
正常的序列化给了我
{"rings":[[{"Location":[0.0,0.0]},{"Location":[1.0,0.0]},{"Location":[2.0,0.0]},{"Location":[0.0,0.0]}]]}
使用自定义转换器非常简单,但是是否有属性方法可以做到这一点,或者这是何时使用 JsonConverter 的完美示例
public class RingPointConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartArray();
writer.WriteValue(((RingPoint)value).X);
writer.WriteValue(((RingPoint)value).Y);
writer.WriteEndArray();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return null;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (RingPoint);
}
}