C#的JSON数据格式转换方法

ASP.NET MVC中Json(value)方法转换成JsonResult格式的数据异步返回给JQuery进行处理,很爽,结果最近不用 ASP.NET MVC开发应用了,异步地区调用涉及到Json数据的获取发现居然没有好的Json格式数据转换方法像过去一样简单调用 很是不爽,搜了下找到个利用System.Runtime.Serialization.Json转换数据的方法,可以转换为JQuery可以识别的格式,不过 调用过程中发现它将实体类的属性名称转换成:”<属性名>k__BackingField ” 这种格式,调用起来很不方便,不过还是将这种方法编写的助手类贴出来: 注意需要引用: 首先,当然是项目是3.5的, 只引用一个System.Runtime.Serialization 是不够的, 还要添加 System.ServiceModel System.ServiceModel.Web 的引用,OK 代码如下:

 

复制代码
/// <summary>
/// FileName: JSONHelper.cs
/// CLRVersion: 2.0.50727.3623
/// Author: Mikel
/// Corporation:
/// Description:JSON格式数据转换助手类
/// 1.将List<T>类型的数据转换为JSON格式
/// 2.将T类型对象转换为JSON格式对象
/// 3.将JSON格式对象转换为T类型对象
/// DateTime: 2011-09-13 14:11:34
/// </summary>
public static class JSONHelper
{
    /// <summary>
    /// 转换对象为JSON格式数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj">对象</param>
    /// <returns>字符格式的JSON数据</returns>
    public static string GetJSON<T>(object obj)
    {
        string result = String.Empty;
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
            new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return result;
    }
    /// <summary>
    /// 转换List<T>的数据为JSON格式
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="vals">列表值</param>
    /// <returns>JSON格式数据</returns>
    public static string JSON<T>(List<T> vals)
    {
        System.Text.StringBuilder st = new System.Text.StringBuilder();
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

            foreach (T city in vals)
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    s.WriteObject(ms, city);
                    st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return st.ToString();
    }
    /// <summary>
    /// JSON格式字符转换为T类型的对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="jsonStr"></param>
    /// <returns></returns>
    public static T ParseFormByJson<T>(string jsonStr)
    {
        T obj = Activator.CreateInstance<T>();
        using (System.IO.MemoryStream ms =
        new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
            new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(ms);
        }
    }
}
复制代码

还是觉得ASP.NET MVC的Json转换比较地道,于是翻找其源码,发现是利用的.net Framework 3.5特有的 c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Web.Extensions.dll 实现的Json数据格式转换,实现代码如下:  

复制代码
namespace System.Web.Mvc {
    using System;
    using System.Text;
    using System.Web;
    using System.Web.Script.Serialization;

    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class JsonResult : ActionResult {

        public Encoding ContentEncoding {
            get;
            set;
        }

        public string ContentType {
            get;
            set;
        }

        public object Data {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context) {
            if (context == null) {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType)) {
                response.ContentType = ContentType;
            }
            else {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null) {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null) {
#pragma warning disable 0618
                JavaScript.Serializer serializer = new JavaScript.Serializer();
                response.Write(serializer.Serialize(Data));
#pragma warning restore 0618
            }
        }
    }
}
复制代码


看到这大家应该明白了,原来.net Framework3.5已经做好了转换的方法,只需要调用即可,不过提醒大家注意: 一定要先引用c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Web.Extensions.dll 才能使用JavaScriptSerializer serializer = new JavaScriptSerializer(); 切记!切记!

博主设置当前文章不允许评论。

没有更多推荐了,返回首页