I need to serialize objects (OpenTK.Vector2
) containing properties with a getter but no setter. I would like these properties to be ignored in general, otherwise I end up with hugely inflated JSON from an object that has two relevant pieces of data (X
and Y
).
The code:
JsonSerializerSettings settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
Vector2 v = new Vector2 { X = 1, Y = 0 };
string json = JsonConvert.SerializeObject(v, settings);
produces the string:
{
"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
}
}
}
}
How can I get the serializer ignore these other properties?