实体和JSON互转

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;
using System.IO;
using System.Text;
/// <summary>
/// Summary description for JsonHelper
/// </summary>
public class JsonHelper
{
    public JsonHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// <summary>
    /// 把对象序列化 JSON 字符串 
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="obj">对象实体</param>
    /// <returns>JSON字符串</returns>
    public static string GetJson<T>(T obj)
    {
        DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream())
        {
            json.WriteObject(ms, obj);
            string szJson = Encoding.UTF8.GetString(ms.ToArray());
            return szJson;
        }
    }
    /// <summary>
    /// 把JSON字符串还原为对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="szJson">JSON字符串</param>
    /// <returns>对象实体</returns>
    public static T ParseFormJson<T>(string szJson)
    {
        T obj = Activator.CreateInstance<T>();
        using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes(szJson)))
        {
            DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
            return (T)dcj.ReadObject(ms);
        }
    }
}
来源于:http://www.cnblogs.com/jinho/archive/2010/04/18/1715044.html
posted @ 2017-04-18 10:36  D调灬仔  阅读(226)  评论(0编辑  收藏  举报

作者D调灬仔

出处:https://www.cnblogs.com/chj929555796/

如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!