C# object to string and back

前端 未结 3 2018
梦毁少年i
梦毁少年i 2021-02-05 16:13

My problem:
I have a dynamic codecompiler which can compile a snippet of code. The rest of the code. (imports, namespace, class, main function) is already there. The snipp

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 16:49

    It's an old question but I think that I have a solution that can work better for most of the times (it creates a shorter string and doesn't require the Serializable attribute).

    The idea is to serialize the object to JSON and then convert it to base64, see the extension function:

    public static string ToBase64(this object obj)
    {
        string json = JsonConvert.SerializeObject(obj);
    
        byte[] bytes = Encoding.Default.GetBytes(json);
    
        return Convert.ToBase64String(bytes);
    }
    

    In order to create the object, we need to convert the base64 to bytes, convert to string and deserialize the JSON to T

    public static T FromBase64(this string base64Text)
    {
        byte[] bytes = Convert.FromBase64String(base64Text);
    
        string json = Encoding.Default.GetString(bytes);
    
        return JsonConvert.DeserializeObject(json);
    }
    

提交回复
热议问题