我需要序列化包含具有getter但没有setter的属性的对象(OpenTK.Vector2
)。我希望一般可以忽略这些属性,否则我最终会从具有两个相关数据片段(X
和Y
)的对象中充分夸大JSON。
代码:
JsonSerializerSettings settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
Vector2 v = new Vector2 { X = 1, Y = 0 };
string json = JsonConvert.SerializeObject(v, settings);
生成字符串:
{
"X" : 1.0,
"Y" : 0.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularRight" : {
"X" : 0.0,
"Y" : -1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularRight" : {
"X" : -1.0,
"Y" : 0.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularRight" : {
"X" : 0.0,
"Y" : 1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0
}
},
"Yx" : {
"X" : -1.0,
"Y" : 0.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularRight" : {
"X" : 0.0,
"Y" : 1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0
}
}
},
"PerpendicularLeft" : {
"X" : 0.0,
"Y" : 1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularLeft" : {
"X" : -1.0,
"Y" : 0.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularLeft" : {
"X" : 0.0,
"Y" : -1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0
},
"Yx" : {
"X" : 0.0,
"Y" : -1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0
}
}
},
"Yx" : {
"X" : 0.0,
"Y" : 1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularLeft" : {
"X" : -1.0,
"Y" : 0.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0,
"PerpendicularLeft" : {
"X" : 0.0,
"Y" : -1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0
},
"Yx" : {
"X" : 0.0,
"Y" : -1.0,
"Length" : 1.0,
"LengthFast" : 1.0016948,
"LengthSquared" : 1.0
}
}
}
}
如何让序列化程序忽略这些其他属性?
答案 0 :(得分:5)
由于您无法修改OpenTK.Vector2
结构以将[JsonIgnore]
属性添加到get-only属性,因此最简单的方法可能是编写自己的JsonConverter
为它:
public class Vector2Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(OpenTK.Vector2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var temp = JObject.Load(reader);
return new OpenTK.Vector2(((float?)temp["X"]).GetValueOrDefault(), ((float?)temp["Y"]).GetValueOrDefault());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var vec = (OpenTK.Vector2)value;
serializer.Serialize(writer, new { X = vec.X, Y = vec.Y});
}
}
然后使用它:
var settings = new JsonSerializerSettings();
settings.Converters.Add(new Vector2Converter());
Vector2 v = new Vector2 { X = 1, Y = 0 };
string json = JsonConvert.SerializeObject(v, settings);
Debug.WriteLine(json);
哪个产生
{"X":1.0,"Y":0.0}
但是如果你真的想忽略所有类和结构上的所有get-only属性(可能会产生无法预料的后果),请参见:Is there a way to ignore get-only properties in Json.NET without using JsonIgnore attributes?。