zoukankan      html  css  js  c++  java
  • 【转】序列化与反序列化

    序列化与反序列化,当对象用来传输

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.IO;

    namespace CodeArt.SharePoint
    {
    /// <summary>
    /// 对象序列化
    /// </summary>
    public static class SerializeUtil
    {
    /// <summary>
    /// 将对象序列化成xml
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string Seralize(object obj)
    {
    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(obj.GetType());

    MemoryStream s = new MemoryStream();
    XmlTextWriter w = new XmlTextWriter(s, Encoding.UTF8);

    //xs.Serialize(w, o, ns);

    xs.Serialize(w, obj);

    string xmlData = Encoding.UTF8.GetString(s.ToArray()).Trim();

    return xmlData;
    }

    /// <summary>
    /// 将xml反序列化成某个对象
    /// </summary>
    /// <param name="t"></param>
    /// <param name="xml"></param>
    /// <returns></returns>
    public static object Deserialize(Type t, string xml)
    {
    System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer( t );

    System.IO.StringReader sw = new System.IO.StringReader(xml);

    return xs.Deserialize(sw) ;
    }
    }
    }

    当一个类的信息要用来传输,只需要在类的顶部加上[Serialize],那么这个类就可以序列化了,并且可以用在页面传值

  • 相关阅读:
    [ZOJ 3622] Magic Number
    SGU 134.Centroid(图心)
    SGU 223.Little Kings
    C++ IO 详细用法
    POJ2632 Crashing Robots 解题报告
    POJ1068 Parencodings 解题报告
    POJ3295 Tautology 解题报告
    POJ2586 Y2K Accounting Bug 解题报告
    POJ1328 Radar Installation 解题报告
    POJ3728 The merchant解题报告
  • 原文地址:https://www.cnblogs.com/gzh4455/p/2438201.html
Copyright © 2011-2022 走看看