zoukankan      html  css  js  c++  java
  • c# json TO xml

    using System.IO;
    using System.Text;
    using System.Xml.Serialization;
    using System.Xml;
    using System.Runtime.Serialization.Json;

    namespace Common.Core
    {
    public class SerializationHelper
    {
    private static string XmlSerialize(object o)
    {
    XmlSerializer ser = new XmlSerializer(o.GetType());
    System.IO.MemoryStream mem = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8);
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");
    ser.Serialize(writer, o, ns);
    writer.Close();
    return Encoding.UTF8.GetString(mem.ToArray());
    }

    private static T XmlDeserialize<T>(string s)
    {
    XmlDocument xdoc = new XmlDocument();
    try
    {
    xdoc.LoadXml(s);
    XmlNodeReader reader = new XmlNodeReader(xdoc.DocumentElement);
    XmlSerializer ser = new XmlSerializer(typeof(T));
    object obj = ser.Deserialize(reader);
    return (T)obj;
    }
    catch
    {
    return default(T);
    }
    }

    private static string JsonSerialize(object o)
    {
    using (var ms = new MemoryStream())
    {
    new DataContractJsonSerializer(o.GetType()).WriteObject(ms, o);
    return Encoding.UTF8.GetString(ms.ToArray());
    }
    }

    private static T JsonDeserialize<T>(string s)
    {
    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(s)))
    {
    return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
    }
    }

    /// <summary>
    /// 将对象根据格式(XML/JSON)序列化成字符串结果
    /// </summary>
    /// <param name="o">目标对象</param>
    /// <param name="format">输出格式</param>
    /// <returns></returns>
    public static string Serialize(object o, Format format)
    {
    if (format == Format.Xml)
    {
    return SerializationHelper.XmlSerialize(o);
    }
    else
    {
    return SerializationHelper.JsonSerialize(o);
    }
    }

    /// <summary>
    /// 将字符串根据格式(XML/JSON)反序列化成指定类型的对象
    /// </summary>
    /// <typeparam name="T">指定类型</typeparam>
    /// <param name="s">目标字符串</param>
    /// <param name="format">输入格式</param>
    /// <returns></returns>
    public static T Deserialize<T>(string s, Format format)
    {
    if (format == Format.Xml)
    {
    return SerializationHelper.XmlDeserialize<T>(s);
    }
    else
    {
    return SerializationHelper.JsonDeserialize<T>(s);
    }
    }
    }
    }

  • 相关阅读:
    YARN简短的建筑
    Codeforces Round #274 (Div. 2) B. Towers
    基于PaaS人事部门间平台多重身份的技术解决方案
    android(9)_数据存储和访问3_scard基本介绍
    google搜索小技巧
    纯CSS实现垂直居中的几种方法
    关于网站的SYN_RECV(SYN_RECEIVED)***的防范措施
    网络的FIN_WAIT_2状态解释和分析
    jQuery对checkbox的各种操作
    0.0.0.0 与 127.0.0.1的区别
  • 原文地址:https://www.cnblogs.com/FredTang/p/4338105.html
Copyright © 2011-2022 走看看