在C#中从base64反序列化对象 [英] Object de-serializing from base64 in C#

查看:153
本文介绍了在C#中从base64反序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级

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

我已经像这样将其转换为JSON

I have converted this to JSON like so

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

然后我将base64编码为JSON字符串

I have then base64 encoded the JSON string

然后我通过网络将其发送到Web api服务

I then send across the wire to a web api service

我收到了base64编码的字符串,现在需要将其反序列化为上述的原始对象(ExternalAccount),所以我首先要做一个

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

下一步是什么?

我尝试了以下操作,但这返回null ...

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.

推荐答案

您可以尝试将字节数组转换回字符串(它将与您发送的JSON相同),然后反序列化到ExternalAccount对象.使用Newtonsoft JSON库,以下示例在控制台上正确显示"Someone":

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

这篇关于在C#中从base64反序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆