0
使用Json.Net 5.0.5
我想序列化這個類序列化類JSON作爲陣列
[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]}]]}
這很簡單做一個自定義轉換器,但有一種屬性的方式來做到這一點,或者這是完美的e什麼時候使用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);
}
}
它只是一個鋸齒狀的陣列: 'double [] [] [] rings = new double [1] [] []; rings [0] = new double [1] []; rings [0] [0] = new double [1]; rings [0] [0] [0] = 3.4;'。不,我會推薦這樣做...... :) –
@JoeEnos是有道理的,我想這可能是。然後我開始考慮列表嵌套和迷惑自己的方式。 – evanmcdonnal