tags:

views:

300

answers:

3

What would be the best method for serializing a Dictionary for use in a single Cookie?

A: 

There are examples of XML-serializable dictionaries out there which would work fine for very small dictionary objects. However, since size is a concern with cookies, I'd recommend exploring something a little less flexible but more compact.

Have you also considered storing the data on the server and just storing a key to the data in the cookie?

Rex M
Yes I have, and I will be storing just the keys in addition to data that isn't saved in the database, at least initially.
Jordan S. Jones
+2  A: 

I don't think Dictionary is marked [Serializable]. If the key and values are primitive types (int, string, etc) you could use a comma/semicolon delimited list:

key1,value1;key2,value2;key3,value3

If you have complex types in your keys/values, I would recommend against serialization. Don't want to deal with 50K cookies, you never know how it will work from browser to browser.

Dave Swersky
Dictionary is marked [Serializable]
Chad Grant
@Deviant IDictionary can only be binary serialized, which is probably not what we want here.
Rex M
@Rex since when can Interfaces be serialized at all? And if you are referring to Dictionary and not IDictionary, I serialize them in JSON all the time. And if you follow the link I provided, Jon Skeet gives some help with Binary to string and back, which is exactly what I was proposing and have done in the past successfully This question doesn't ask about XML at all so don't understand your point.
Chad Grant
@Deviant XML serialization is used as the basis for a number of other kinds of serializations, so it's important to note. Regarding IDictionary, it is the interface which prevents serialization, in that the serializer checks to see if the incoming object implements IDictionary.
Rex M
+1  A: 

I don't recommend it, the performance of serializing/deserializing a cookie on every request is terrible.

Figure out a way to represent the structure yourself to/from a string.

If you absolutely must serialize it:

http://petesbloggerama.blogspot.com/2006/07/binary-serialization-to-from-string.html

Chad Grant