Wednesday, January 22, 2014

Ignoring properties when serializing to JSON using JSON.NET

I ran into this particular issue while using SignalR, but it would happen in any case where you are serializing data to JSON using Newtonsoft’s JSON.NET library.  I was finding that properties on my C# object were clearly marked with the [ScriptIgnore] attribute were still being serialized, which was sending unnecessary data down to the browser.


1
2
3
4
5
6
7
8
[ScriptIgnore]
public string TileName
{
get
{
return Tile.GetTileName(this.TileCode);
}
}

The answer turned out to be simple: SignalR uses JSON.NET behind the scenes to do the heavy serialization lifting, and JSON.NET looks for the [JsonIgnore] attribute instead.







1
2
3
4
5
6
7
8
[JsonIgnore]
public string TileName
{
get
{
return Tile.GetTileName(this.TileCode);
}
}

If only all of my annoying little bugs were this easy to solve!

  

No comments: