2

DataContractJsonSerializer を使用してバルク データをシリアル化していますが、エラーが発生しています。タイプ 'System.OutOfMemoryException' の例外がスローされました。

public static string MyDataContractJsonSerializer(object objToSerialize, Type objType)
{
        DataContractJsonSerializer ser = new DataContractJsonSerializer(objType);
        System.IO.MemoryStream st1 = new System.IO.MemoryStream();
        ser.WriteObject(st1, objToSerialize);  //Error encountering here.. Exception of type 'System.OutOfMemoryException' was thrown.
        byte[] barray = st1.ToArray(); 
        string abc = System.Text.Encoding.ASCII.GetString(barray);
        return abc;
}

この問題を解決するにはどうすればよいですか?

バルク データをシリアル化する別の方法を教えてください。

私を助けてください。

4

3 に答える 3

0

これは、シリアル化するオブジェクトのサイズが無制限であるためです。

大きなオブジェクトの場合は、小さなチャンクに分割して、1 つずつシリアル化することをお勧めします。

于 2012-10-09T12:36:26.727 に答える
0

ストリーム (つまり、FileStream) にシリアル化することもできます。このようにして、OutOfMemory 例外なしでギガバイトのデータをシリアル化できます。

        public static void Serialize<T>(T obj, string path)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            Stream stream = File.OpenWrite(path);
            serializer.WriteObject(stream, obj);
        }

        public static T Deserialize<T>(string path)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            Stream stream = File.OpenRead(path);
            return (T)serializer.ReadObject(stream);
        }
于 2016-10-24T06:33:30.517 に答える
0

In the comments section you mentioned that you want to send the serialized data to the client browser (javascript client). In this case you should not be serializing the object into a MemoryStream. That's a useless waste of memory. If this is an ASP.NET application you could directly serialize the object to the Response.OutputStream.

For example your method could look like this:

public static void MyDataContractJsonSerializer(
    object objToSerialize, 
    Type objType, 
    Stream output
)
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(objType);
    ser.WriteObject(output, objToSerialize);
}

and then when invoking the method directly pass the response output stream. For example if you are calling this method from a generic ASHX handler:

public class MyHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";

        var objToSerialize = ...

        SerializerClass.MyDataContractJsonSerializer(
            objToSerialize, 
            objToSerialize.GetType(), 
            context.Response.OutputStream
        );
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
于 2012-10-09T14:00:17.033 に答える