Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object de-serializing from base64 in C#

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.

like image 627
AdrianSean Avatar asked Jul 10 '15 11:07

AdrianSean


1 Answers

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; }
}
like image 122
Volkan Paksoy Avatar answered Sep 17 '22 19:09

Volkan Paksoy