0

What is the best practice way to override the serialization (serialisation) for a class?

Specifically I have Key/Value pair collection. The default generated JSON looks like this:

[{"Key":1,"Value":"A"},{"Key":2,"Value":"B"},{"Key":3,"Value":"C"},{"Key":4,"Value":"D"},{"Key":5,"Value":"E"},{"Key":6,"Value":"F"}]

Which is very wasteful.

I would like to override it to produce something more like this: [{"1":"A":},{"2":"B":},{"3":"C":},{"4":"D":},{"5":"E":},{"6":"F":}]

Which is one byte off of being half the length, and easier to use at the javascript end.

Implementing ISerliazable doesn't seem to work - I think the json serializer is ignoring it

Google found me this http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx But to me this looks like a hideous way of doing things - surely there must be a better way?

DJL
  • 2,060
  • 3
  • 20
  • 39

1 Answers1

0

Ok so here's the odd thing.

I changed my collection to a SortedList and it actually gave me the json I was after.

So this works for my specific example but I can imagine there will be other occasions I might want to override the serialization.

DJL
  • 2,060
  • 3
  • 20
  • 39