Serialize object to string

。_饼干妹妹 提交于 2019-12-11 07:01:10

问题


I am working on a TCP/IP project, I need to send encrypted packages via sockets. I've completed network part, I can send strings but all my packages are objects. So I have to serialize my package class to string and encrypt it, then after client receives deserialize and decrypt it. Cany you help me please?

Package.cs

 public class Package
{
    private string context;
    public string Context
    {
        get { return context; }
        set { context = value; }
    }
    private bool flag;
    public bool Flag
    {
        get { return flag; }
        set { flag = value; }
    }
    private int statusCode;
    public int StatusCode
    {
        get { return statusCode; }
        set { statusCode = value; }
    }

    public Package() { this.context = null; }
}

回答1:


For serialization you can use JavaScriptSerializer class.

Add reference System.Web.Extensions to your project then;

private string Serialize(object obj){
var serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}

private object Deserialize(string json){
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<object>(json);
}

For encryption/decryption you can basically use Base64 but if you want more spesific answer, you need to tell more details about your requirements.



来源:https://stackoverflow.com/questions/45455188/serialize-object-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!