Object de-serializing from base64 in C#

2020-06-22 15:34发布

问题:

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.

回答1:

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; }
}


回答2:

you need to extract string from the bytes you recieve.

byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);
string AccountInfo = System.Text.Encoding.UTF8.GetString(byteArray );

As expected, you will get {\"Name\":\"XYZ\"} in your AccountInfo string. Now you need to Deserialize. you can use the same model, ExternalAccount. you may do something like:

ExnternalAccount model = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<ExnternalAccount>(AccountInfo );