Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将对象序列化为字符串_C#_String_Serialization_Xml Serialization - Fatal编程技术网

C# 将对象序列化为字符串

C# 将对象序列化为字符串,c#,string,serialization,xml-serialization,C#,String,Serialization,Xml Serialization,我使用以下方法将对象保存到文件: // Save an object out to the disk public static void SerializeObject<T>(this T toSerialize, String filename) { XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType()); TextWriter textWriter = new StreamWr

我使用以下方法将对象保存到文件:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    TextWriter textWriter = new StreamWriter(filename);

    xmlSerializer.Serialize(textWriter, toSerialize);
    textWriter.Close();
}
//将对象保存到磁盘
公共静态void serialize对象(此T-toSerialize,字符串文件名)
{
XmlSerializer XmlSerializer=新的XmlSerializer(toSerialize.GetType());
TextWriter TextWriter=新的StreamWriter(文件名);
序列化(textWriter,toSerialize);
textWriter.Close();
}
我承认我并没有编写它(我只是将它转换为一个带有类型参数的扩展方法)

现在,我需要它将xml作为字符串返回给我(而不是将其保存到文件)。我正在调查,但还没有弄明白

我想这对熟悉这些物体的人来说可能真的很容易。如果没有,我最终会解决的。

用a代替a:

公共静态字符串序列化对象(此T序列化)
{
XmlSerializer XmlSerializer=新的XmlSerializer(toSerialize.GetType());
使用(StringWriter textWriter=new StringWriter())
{
序列化(textWriter,toSerialize);
返回textWriter.ToString();
}
}
注意,在XmlSerializer构造函数中使用
toSerialize.GetType()
而不是
typeof(T)
非常重要:如果使用第一个,代码将覆盖
T
的所有可能子类(对该方法有效),而在传递从
T
派生的类型时,使用后一个将失败   下面是一些示例代码的链接,这些代码激发了这条语句,当使用
typeof(T)
时,
XmlSerializer
抛出一个
异常,因为您将派生类型的实例传递给调用派生类型基类中定义的SerializeObject的方法:

此外,Ideone使用单声道执行代码;使用Microsoft.NET运行时会出现的实际
异常
与Ideone上显示的
消息不同,但失败的原因相同。

代码安全注意事项 关于,在
XmlSerializer
构造函数中使用
toSerialize.GetType()
而不是
typeof(T)
是很重要的:如果使用第一个构造函数,代码将覆盖所有可能的场景,而使用后一个构造函数有时会失败

下面是一些示例代码的链接,这些代码激发了这条语句,当使用
typeof(T)
时,
XmlSerializer
抛出异常,因为您将派生类型的实例传递给调用派生类型基类中定义的
SerializeObject()
的方法。请注意,Ideone使用Mono来执行代码:使用Microsoft.NET运行时会得到的实际异常与Ideone上显示的消息不同,但它同样失败

为了完整起见,我将完整的代码示例发布在此处以供将来参考,以防将来无法使用Ideone(我发布代码的地方):

using System;
using System.Xml.Serialization;
using System.IO;

public class Test
{
    public static void Main()
    {
        Sub subInstance = new Sub();
        Console.WriteLine(subInstance.TestMethod());
    }

    public class Super
    {
        public string TestMethod() {
            return this.SerializeObject();
        }
    }

    public class Sub : Super
    {
    }
}

public static class TestExt {
    public static string SerializeObject<T>(this T toSerialize)
    {
        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();

        // And now...this will throw and Exception!
        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType()); 
        // solves the problem
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}
使用系统;
使用System.Xml.Serialization;
使用System.IO;
公开课考试
{
公共静态void Main()
{
Sub subInstance=new Sub();
WriteLine(subInstance.TestMethod());
}
公共级超级
{
公共字符串TestMethod(){
返回此.SerializeObject();
}
}
公开课分组:超级
{
}
}
公共静态类TestExt{
公共静态字符串序列化对象(此T-toSerialize)
{
Console.WriteLine(typeof(T.Name);//打印:“Super”,基/超类——预期输出为“Sub”
Console.WriteLine(toSerialize.GetType().Name);//打印:“Sub”,派生的/子类
XmlSerializer XmlSerializer=新的XmlSerializer(typeof(T));
StringWriter textWriter=新StringWriter();
//现在…这将抛出异常!
//将新的XmlSerializer(typeof(T))更改为新的XmlSerializer(subInstance.GetType());
//解决问题
序列化(textWriter,toSerialize);
返回textWriter.ToString();
}
}

我知道这不是问题的真正答案,但根据问题的投票数和接受的答案,我怀疑人们实际上是在使用代码将对象序列化为字符串

使用XML序列化将不必要的额外文本垃圾添加到输出中

下节课

public class UserData
{
    public int UserId { get; set; }
}
它产生

<?xml version="1.0" encoding="utf-16"?>
<UserData xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <UserId>0</UserId>
</UserData>
要反序列化对象,请执行以下操作:

var userData = new UserData {UserId = 0};
var userDataString = JsonConvert.SerializeObject(userData);
var userData = JsonConvert.DeserializeObject<UserData>(userDataString);
序列化和反序列化(XML/JSON):

public static T xml反序列化(此字符串要进行序列化)
{
XmlSerializer XmlSerializer=新的XmlSerializer(typeof(T));
使用(StringReader文本阅读器=新的StringReader(进行序列化))
{      
返回(T)xmlSerializer.Deserialize(textReader);
}
}
公共静态字符串XmlSerialize(此T-toSerialize)
{
XmlSerializer XmlSerializer=新的XmlSerializer(typeof(T));
使用(StringWriter textWriter=new StringWriter())
{
序列化(textWriter,toSerialize);
返回textWriter.ToString();
}
}
公共静态T JsonDeserialize(此字符串用于序列化)
{
返回JsonConvert.DeserializeObject(toDeserialize);
}
公共静态字符串JsonSerialize(此T-toSerialize)
{
返回JsonConvert.SerializeObject(toSerialize);
}
我的2p

        string Serialise<T>(T serialisableObject)
        {
            var xmlSerializer = new XmlSerializer(serialisableObject.GetType());

            using (var ms = new MemoryStream())
            {
                using (var xw = XmlWriter.Create(ms, 
                    new XmlWriterSettings()
                        {
                            Encoding = new UTF8Encoding(false),
                            Indent = true,
                            NewLineOnAttributes = true,
                        }))
                {
                    xmlSerializer.Serialize(xw,serialisableObject);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
        }
string序列化(T serialisableObject)
{
var xmlSerializer=新的xmlSerializer(serialisableObject.GetType());
使用(var ms=new MemoryStream())
{
使用(var xw=XmlWriter.Create)(ms,
新的XmlWriterSettings()
{
编码=新的UTF8编码(错误),
缩进=真,
NewLineOnAttributes=true,
}))
{
Serialize(xw,serialisableObject);
重新
{"UserId":0}
public static T XmlDeserialize<T>(this string toDeserialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using(StringReader textReader = new StringReader(toDeserialize))
    {      
        return (T)xmlSerializer.Deserialize(textReader);
    }
}

public static string XmlSerialize<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using(StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

public static T JsonDeserialize<T>(this string toDeserialize)
{
    return JsonConvert.DeserializeObject<T>(toDeserialize);
}

public static string JsonSerialize<T>(this T toSerialize)
{
    return JsonConvert.SerializeObject(toSerialize);
}
        string Serialise<T>(T serialisableObject)
        {
            var xmlSerializer = new XmlSerializer(serialisableObject.GetType());

            using (var ms = new MemoryStream())
            {
                using (var xw = XmlWriter.Create(ms, 
                    new XmlWriterSettings()
                        {
                            Encoding = new UTF8Encoding(false),
                            Indent = true,
                            NewLineOnAttributes = true,
                        }))
                {
                    xmlSerializer.Serialize(xw,serialisableObject);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
        }
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonstring = js.Serialize(yourClassObject);
public string name {get;set;}
public int age {get;set;}

Person(string serializedPerson) 
{
    string[] tmpArray = serializedPerson.Split('\n');
    if(tmpArray.Length>2 && tmpArray[0].Equals("#")){
        this.name=tmpArray[1];
        this.age=int.TryParse(tmpArray[2]);
    }else{
        throw new ArgumentException("Not a valid serialization of a person");
    }
}

public string SerializeToString()
{
    return "#\n" +
           name + "\n" + 
           age;
}
public static string SerializeObject<T>(T objectToSerialize)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            MemoryStream memStr = new MemoryStream();

            try
            {
                bf.Serialize(memStr, objectToSerialize);
                memStr.Position = 0;

                return Convert.ToBase64String(memStr.ToArray());
            }
            finally
            {
                memStr.Close();
            }
        }

        public static T DerializeObject<T>(string objectToDerialize)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            byte[] byteArray = Convert.FromBase64String(objectToDerialize);
            MemoryStream memStr = new MemoryStream(byteArray);

            try
            {
                return (T)bf.Deserialize(memStr);
            }
            finally
            {
                memStr.Close();
            }
        }
Public Function XmlSerializeObject(ByVal obj As Object) As String

    Dim xmlStr As String = String.Empty

    Dim settings As New XmlWriterSettings()
    settings.Indent = False
    settings.OmitXmlDeclaration = True
    settings.NewLineChars = String.Empty
    settings.NewLineHandling = NewLineHandling.None

    Using stringWriter As New StringWriter()
        Using xmlWriter__1 As XmlWriter = XmlWriter.Create(stringWriter, settings)

            Dim serializer As New XmlSerializer(obj.[GetType]())
            serializer.Serialize(xmlWriter__1, obj)

            xmlStr = stringWriter.ToString()
            xmlWriter__1.Close()
        End Using

        stringWriter.Close()
    End Using

    Return xmlStr.ToString
End Function

Public Function XmlDeserializeObject(ByVal data As [String], ByVal objType As Type) As Object

    Dim xmlSer As New System.Xml.Serialization.XmlSerializer(objType)
    Dim reader As TextReader = New StringReader(data)

    Dim obj As New Object
    obj = DirectCast(xmlSer.Deserialize(reader), Object)
    Return obj
End Function
public string XmlSerializeObject(object obj)
{
    string xmlStr = String.Empty;
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = false;
    settings.OmitXmlDeclaration = true;
    settings.NewLineChars = String.Empty;
    settings.NewLineHandling = NewLineHandling.None;

    using (StringWriter stringWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
        {
            XmlSerializer serializer = new XmlSerializer( obj.GetType());
            serializer.Serialize(xmlWriter, obj);
            xmlStr = stringWriter.ToString();
            xmlWriter.Close();
        }
    }
    return xmlStr.ToString(); 
}

public object XmlDeserializeObject(string data, Type objType)
{
    XmlSerializer xmlSer = new XmlSerializer(objType);
    StringReader reader = new StringReader(data);

    object obj = new object();
    obj = (object)(xmlSer.Deserialize(reader));
    return obj;
}
using System;
using System.Xml.Serialization;
using System.IO;

namespace ObjectSerialization
{
    public static class ObjectSerialization
    {
        // THIS: (C): https://stackoverflow.com/questions/2434534/serialize-an-object-to-string
        /// <summary>
        /// A helper to serialize an object to a string containing XML data of the object.
        /// </summary>
        /// <typeparam name="T">An object to serialize to a XML data string.</typeparam>
        /// <param name="toSerialize">A helper method for any type of object to be serialized to a XML data string.</param>
        /// <returns>A string containing XML data of the object.</returns>
        public static string SerializeObject<T>(this T toSerialize)
        {
            // create an instance of a XmlSerializer class with the typeof(T)..
            XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

            // using is necessary with classes which implement the IDisposable interface..
            using (StringWriter stringWriter = new StringWriter())
            {
                // serialize a class to a StringWriter class instance..
                xmlSerializer.Serialize(stringWriter, toSerialize); // a base class of the StringWriter instance is TextWriter..
                return stringWriter.ToString(); // return the value..
            }
        }

        // THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
        /// <summary>
        /// Deserializes an object which is saved to an XML data string. If the object has no instance a new object will be constructed if possible.
        /// <note type="note">An exception will occur if a null reference is called an no valid constructor of the class is available.</note>
        /// </summary>
        /// <typeparam name="T">An object to deserialize from a XML data string.</typeparam>
        /// <param name="toDeserialize">An object of which XML data to deserialize. If the object is null a a default constructor is called.</param>
        /// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
        /// <returns>An object which is deserialized from the XML data string.</returns>
        public static T DeserializeObject<T>(this T toDeserialize, string xmlData)
        {
            // if a null instance of an object called this try to create a "default" instance for it with typeof(T),
            // this will throw an exception no useful constructor is found..
            object voidInstance = toDeserialize == null ? Activator.CreateInstance(typeof(T)) : toDeserialize;

            // create an instance of a XmlSerializer class with the typeof(T)..
            XmlSerializer xmlSerializer = new XmlSerializer(voidInstance.GetType());

            // construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
            using (StringReader stringReader = new StringReader(xmlData))
            {
                // return the "new" object deserialized via the XmlSerializer class instance..
                return (T)xmlSerializer.Deserialize(stringReader);
            }
        }

        // THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
        /// <summary>
        /// Deserializes an object which is saved to an XML data string.
        /// </summary>
        /// <param name="toDeserialize">A type of an object of which XML data to deserialize.</param>
        /// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
        /// <returns>An object which is deserialized from the XML data string.</returns>
        public static object DeserializeObject(Type toDeserialize, string xmlData)
        {
            // create an instance of a XmlSerializer class with the given type toDeserialize..
            XmlSerializer xmlSerializer = new XmlSerializer(toDeserialize);

            // construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
            using (StringReader stringReader = new StringReader(xmlData))
            {
                // return the "new" object deserialized via the XmlSerializer class instance..
                return xmlSerializer.Deserialize(stringReader);
            }
        }
    }
}