ProgramingTip

DataContractSerializer를 사용하여 생성 화하지만 역화 할 수 없음

bestdevel 2020. 11. 22. 20:22
반응형

DataContractSerializer를 사용하여 생성 화하지만 역화 할 수 없음


다음 두 가지 기능이 있습니다.

public static string Serialize(object obj)
{
    DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
    MemoryStream memoryStream = new MemoryStream();
    serializer.WriteObject(memoryStream, obj);
    return Encoding.UTF8.GetString(memoryStream.GetBuffer());
}

public static object Deserialize(string xml, Type toType)
{
    MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
   // memoryStream.Position = 0L;
    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
    DataContractSerializer dataContractSerializer = new DataContractSerializer(toType);
    return dataContractSerializer.ReadObject(reader);
}

첫 번째는 것입니다. XML은 유효하고, 더러워진 태그가없고, 시작 또는 공백이없는 것처럼 보입니다. 이제 두 번째 함수는 내 xml 어디에 다시 개체로 역화하지 않고 고합니다. 마지막 줄에서 다음을 얻습니다.

[MY OBJECT TYPE HERE] 유형의 개체를 역화하는 중에 오류가 발생했습니다. 루트 수준의 데이터가 잘못되었습니다. 라인 1, 위치 1

내가 도대체 ​​뭘 잘못하고있는 겁니까? Deserialize 함수를 몇 번에 다시 작성하려고 할 때 항상 같은 종류의 오류 인 것입니다. 감사합니다!

아, 내가 이것이 두 가지 함수를 호출하는 방법입니다.

SomeObject so = new SomeObject();
string temp = SerializationManager.Serialize(so);
so = (SomeObject)SerializationManager.Deserialize(temp, typeof(SomeObject));

내가 항상해온 방법은 다음과 가변합니다.

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }


다른 솔루션은 다음과 가변합니다.

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

한 가지 포함되는 내용 : 원시 xml에 다음과 같은 내용이 있습니다.

<?xml version="1.0" encoding="utf-16"?>

물론 다른 예제에서 사용 된 UTF8 인코딩을 사용할 수 없습니다.


나는 다음을 끝내고 작동합니다.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

stream.GetBuffer ()를 호출 할 때 Serialize 함수에 주요 문제가 있었던 것 같습니다. stream.ToArray () 호출이 작동하는 것 같습니다.


XML 역 직렬화에 가장 적합합니다.

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

참고 URL : https://stackoverflow.com/questions/5010191/using-datacontractserializer-to-serialize-but-cant-deserialize-back

반응형