简体   繁体   中英

How to serialize Dictionary into base64

I need to serialize the headers object to store it in string format, probably base64. The Dictionary<String, Object> will only have String or Int values, so there should be no problem.

 Dictionary<String, Object> headers = RequestHeaders.ProcessHeaders(HttpContext.Current); 

Also, of course the point is to be able to deserialize the base64 string back to Dictionary.

You can't serialize a Dictionary into XML, but you could serialize it into JSON:

string json = JsonConvert.SerializeObject(dictionary, Formatting.None);
byte[] bytes = Encoding.UTF8.GetBytes(json);
string base64String = Convert.ToBase64String(bytes);`

To deserialize:

byte[] bytes = Convert.FromBase64String(base64String);
string json = Encoding.UTF8.GetString(bytes);
Dictionary<string, object> deserializedDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

Firstly can I clarify that you cannot Serialize from Dictionary to Base64, because Dictionary is a structure, Base64 is an encoding format.

You need to serialize from Dictionary to XML (not supported by .NET but you can build your own serializer/deserializer for this, or use a 3rd party one), or JSON, or even Binary if it does not need to be human readable. Then, you can encode the result of the serialization to Base64.

ASP.NET ViewStates work similar to this (however I don't think a ViewState is a dictionary), but it is a structure which is serialized and then Base64 encoded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM