Object de-serializing from base64 in C#

AdrianSean picture AdrianSean · Jul 10, 2015 · Viewed 24.1k times · Source

I have a class as so

[Serializable]
public class ExternalAccount
{
  public string Name { get;set;}      
}

I have converted this to JSON like so

{\"Name\":\"XYZ\"}

I have then base64 encoded the JSON string

I then send across the wire to a web api service

I receive the base64 encoded string and now need to de-serialize it back to the original object as above (ExternalAccount) so i firstly do a

byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);

What is the next step?

I have tried the below but this returns null...

using (MemoryStream memoryStream = new MemoryStream(byteArrayToConvert))
 {
            BinaryFormatter binaryFormatter = new BinaryFormatter();

            // set memory stream position to starting point
            memoryStream.Position = 0;

            // Deserializes a stream into an object graph and return as a               object.
            return binaryFormatter.Deserialize(memoryStream) as ExternalAccount;
  }

Any pointers/tips greatly appreciated.

Answer

Volkan Paksoy picture Volkan Paksoy · Jul 10, 2015

You can try converting the byte array back to string (it will be the same JSON you sent), then deserialize to the ExternalAccount object. Using the Newtonsoft JSON library the following sample correctly displays "Someone" on the console:

class Program
{
    static void Main(string[] args)
    {
        var account = new ExternalAccount() { Name = "Someone" };
        string json = JsonConvert.SerializeObject(account);
        string base64EncodedExternalAccount = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
        byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);

        string jsonBack = Encoding.UTF8.GetString(byteArray);
        var accountBack = JsonConvert.DeserializeObject<ExternalAccount>(jsonBack);
        Console.WriteLine(accountBack.Name);
        Console.ReadLine();
    }
}

[Serializable]
public class ExternalAccount
{
    public string Name { get; set; }
}