zoukankan      html  css  js  c++  java
  • Rest中的XML与JSON的序列化与反序列化

    #region 获取XML的序列化和反序列化
    /// <summary>
    /// 对象进行序列化生成XML
    /// </summary>
    /// <typeparam name="T">需要序列化的对象类型</typeparam>
    /// <param name="obj">需要序列化的对象</param>
    /// <returns>序列化后的XML</returns>
    public static string DataContractXmlSerialize<T>(T obj)
    {
    if (obj == null)
    {
    return null;
    }
    string ret = "";
    using (MemoryStream stream = new MemoryStream())
    {
    DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
    using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
    {
    serializer.WriteObject(binaryDictionaryWriter, obj);
    binaryDictionaryWriter.Flush();
    }
    ret = Encoding.UTF8.GetString(stream.ToArray());
    }
    return ret;
    }
    /// <summary>
    /// XML反序列化生成对象
    /// </summary>
    /// <typeparam name="T">反序列化生成对象类型</typeparam>
    /// <param name="xml">XML内容</param>
    /// <returns>反序列化生成对象</returns>
    public static T DataContractXmlDeserialize<T>(string xml)
    {
    T ret = default(T);
    if (string.IsNullOrEmpty(xml))
    {
    return ret;
    }
    using (MemoryStream stream = new MemoryStream())
    {
    byte[] bytes = Encoding.UTF8.GetBytes(xml);
    stream.Write(bytes, 0, bytes.Length);
    stream.Position = 0L;
    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
    using (XmlDictionaryReader binaryDictionaryReader = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max))
    {
    ret = (T)serializer.ReadObject(binaryDictionaryReader);
    }
    }
    return ret;
    }
    #endregion

    #region 获取JSON的序列化和反序列化
    /// <summary>
    /// JSON序列化
    /// </summary>
    public static string DataContractJsonSerializer<T>(T t)
    {
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    MemoryStream ms = new MemoryStream();
    ser.WriteObject(ms, t);
    string jsonString = Encoding.UTF8.GetString(ms.ToArray());
    ms.Close();
    return jsonString;
    }

    /// <summary>
    /// JSON反序列化
    /// </summary>
    public static T DataContractJsonDeserialize<T>(string jsonString)
    {
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    T obj = (T)ser.ReadObject(ms);
    return obj;
    }
    #endregion

  • 相关阅读:
    gil
    异步
    字符串 最长回文字串
    字符串 最长公共前缀
    数组 合并区间
    python 排序
    2021.9.3 阿里笔试AK贴
    SIP协议详解
    fiddler抓包各字段的含义
    常见的HTTP状态码列表
  • 原文地址:https://www.cnblogs.com/elim/p/3680794.html
Copyright © 2011-2022 走看看