将String转换为类

时间:2012-08-14 07:06:26

标签: c# asp.net

我有一个班级AuthUser

public class AuthUser
{
    public int UserID { get; set; }
    public string UserNo { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

我已将班级转换为string

AuthUser au = new AuthUser();
//dtUserDetails is a data table
if (dtUserDetails.Rows.Count > 0)
{
    DataRow DR = dtUserDetails.Rows[0];
    au.UserID = Convert.ToInt32(DR["UserID"].ToString());
    au.UserNo = DR["UserNo"].ToString();
    au.UserName = DR["UserName"].ToString();
    au.Password = DR["Password"].ToString();
}
string userData = au.ToString();

现在我需要将上面的UserData字符串转换回对象类型以检索数据。我怎么能这样做?

3 个答案:

答案 0 :(得分:5)

我假设您正在尝试保留数据,然后从持久数据重建对象。查看Serialization

答案 1 :(得分:0)

试试这个

您可以将其设为匿名类型

public static string ObjectToXMLString(Object anyObject)
{
    string XmlizedString = string.Empty;
    XmlSerializer xs = null;
    XmlTextWriter xmlTextWriter = null;
    MemoryStream memoryStream = new MemoryStream();
    try
    {
        xs = new XmlSerializer(anyObject.GetType());
        xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.Unicode);
        xs.Serialize(xmlTextWriter, anyObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = Encoding.Unicode.GetString(memoryStream.ToArray());
    }
    catch 
    {
        //Do nothing for now
    }
    finally
    {
        xmlTextWriter.Close();
        memoryStream.Close();
    }
    return XmlizedString;
}

并再次将其转回

/// <summary>
/// XMLs the string to object.
/// </summary>
/// <typeparam name="T">Object of target type</typeparam>
/// <param name="xml">The XML.</param>
/// <returns>Instance of target type object filled with corresponding xml data.</returns>
public static T XMLStringToObject<T>(string xml)
{
    // create default instance of the target type object
    T targetObject = default(T);

    // init serializer params
    XmlSerializer ser = null;
    StringReader stringReader = null;
    XmlTextReader xmlReader = null;
    try
    {
        // start deserialization of object 
        ser = new XmlSerializer(typeof(T));
        stringReader = new StringReader(xml);
        xmlReader = new XmlTextReader(stringReader);
        targetObject = (T)ser.Deserialize(xmlReader);
    }
    catch(Exception ex)
    {
        // determine what type of object was the target and a copy of the xml being tried and rethrow
        throw new ArgumentException(String.Format("Exception while deseriliazing to object of type {0}.\n\n=== XML ========\n{1}", typeof(T), xml), ex);
    }
    finally
    {
        // always close readers to release objectToXMLString
        xmlReader.Close();
        stringReader.Close();
    }

    // return target objectToXMLString
    return targetObject;
}

答案 2 :(得分:0)

使用序列化,你可以像这样创建一个JsonSerilizer:

public static class JsonUtil
{
    public static string Serialize<T>(T value)
    {
        using (var ms = new MemoryStream())
        {
            var ser = new DataContractJsonSerializer(typeof(T));
            ser.WriteObject(ms, value);
            byte[] json = ms.ToArray();
            ms.Close();
            return Encoding.UTF8.GetString(json, 0, json.Length);
        }
    }

    public static T Deserialise<T>(string json)
    {
        using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(memoryStream);
        }
    }

}

像这样使用:

// Create an object
var dude = new Dude() { Id = 1, Name = "Joe Smith" };

// Turn it into a string
var json = JsonUtil.Serialize<Dude>(dude);

// Turn it back into an object
var cloneDude = JsonUtil.Deserialise<Dude>(json);