3

I want to change the default serializer in Newtonsoft.Json for System.Drawing.Color. Instead of the default string value I would like to fire this method:

public string ToHtml(Color c)
    => $"rgba({c.R},{c.G},{c.B},{c.A / 255f})";

Every time an object of type Color is to be resolved. This is the format to be consumed by CSS.

What is an elegant, yet simple way to accomplish this?

EDIT

Here is an example json I want to create:

{
  "color": "rgba(80,80,80,0.5)"
}
Community
  • 1
  • 1
ebvtrnog
  • 4,167
  • 4
  • 31
  • 59
  • 3
    Google a bit please... http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/ – Gusman Feb 06 '16 at 21:55
  • You would make a `JsonConverter` like the `ColorConverter` here: https://stackoverflow.com/questions/29421904/how-to-use-a-jsonconverter-with-jtoken-toobject-method – dbc Feb 06 '16 at 21:57
  • Can you give an example of the JSON you want to create? It's not clear from your question if you're trying to embed a string in your json, or a [JConstructor](http://stackoverflow.com/questions/25351479/why-is-jconstructor). – dbc Feb 06 '16 at 22:02
  • 1
    @dbc example json added :) – ebvtrnog Feb 06 '16 at 22:04
  • got it working, thanks! – ebvtrnog Feb 06 '16 at 22:08
  • 1
    Glad to hear that you got it working. Please consider [answering your own question](http://stackoverflow.com/help/self-answer), so that others can profit from your learning experience. – Heinzi Feb 06 '16 at 22:11

0 Answers0