.NET下 JSON 的一些常用操作

1.JSON的序列化和反序列化

首先要先添加引用:

代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace PlayJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            List list = new List() { new StuInfo{StuName="张三",StuSex="男",StuAge=11},
                                                       new StuInfo{StuName="李四",StuSex="男",StuAge=32},
                                                       new StuInfo{StuName="王翠花",StuSex="女",StuAge=64}
                                                      };
            string jsonStr = JavaScriptConvert.SerializeObject(list);  //将对象转换成json存储
            Console.WriteLine("JSON字符串"+jsonStr);
            Console.ReadLine();

            List newList = new List();

           newList = (List)JavaScriptConvert.DeserializeObject(jsonStr,typeof(List));   //反序列化

            //StuInfo s = new StuInfo() { StuName = "阿龙", StuSex = "男", StuAge = 33 };

            //string sigleJSON = JavaScriptConvert.SerializeObject(s);

           //StuInfo newS = (StuInfo)JavaScriptConvert.DeserializeObject(sigleJSON);
           //Console.WriteLine("姓名:" + newS.StuName + "---性别:" + newS.StuSex + "--年龄:" + newS.StuAge + "\n\n");


           foreach (StuInfo item in newList)
           {
               Console.WriteLine("姓名:" + item.StuName + "---性别:" + item.StuSex + "--年龄:" + item.StuAge + "\n\n");
           }
            Console.ReadLine();
        }
    }
    public class StuInfo 
    {
        public string StuName { set; get; }
        public string StuSex { set; get; }
        public int StuAge { set; get; }
    }
}

2.在web中

首先添加一个一般处理文件 Handler1.ashx:用来返回一个json

/// 
    /// Handler1 的摘要说明
    /// 
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            List list = new List() { new StuInfo{StuName="张三",StuSex="男",StuAge=11},
                                                       new StuInfo{StuName="李四",StuSex="男",StuAge=32},
                                                       new StuInfo{StuName="王翠花",StuSex="女",StuAge=64}
                                                      };
            string jsonStr = JavaScriptConvert.SerializeObject(list);

            context.Response.Write(jsonStr);

            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    public class StuInfo
    {
        public string StuName { set; get; }
        public string StuSex { set; get; }
        public int StuAge { set; get; }
    }

前台页面上的调用:这里采用jquery 的ajax请求


    JSON
    
    


    

现在经常会用到json,因此经常会需要对其进行序列化和反序列化。,.NET Framewok 3.5也提供了JSON对象序列化和反序列化的类,这就是System.Runtime.Serialization.Json 命名空间下的 DataContractJsonSerializer 类。利用这个类,可以实现JSON对象的序列化和反序列化。

现在我提供一个类JSON对象序列化和反序列化的类供参考用:

/// 
    /// JSON帮助类。用于将对象转换为Json格式的字符串,或者将Json的字符串转化为对象。
    /// 
    public static class JsonHelper
    {
        /// 
        /// 将对象转化为Json字符串 
        /// 
        /// 源类型
        /// 源类型实例
        /// Json字符串
        public static string GetJsonFromObj(T obj)
        {
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                jsonSerializer.WriteObject(ms, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }

        /// 
        /// 将Json字符串转化为对象
        /// 
        /// 目标类型
        /// Json字符串
        /// 目标类型的一个实例
        public static T GetObjFromJson(string strJson)
        {
            T obj = Activator.CreateInstance();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
                return (T)jsonSerializer.ReadObject(ms);
            }
        }

        /// 
        /// 将DataTable转换为JSON字符串
        /// 
        /// 数据表
        /// JSON字符串
        public static string GetJsonFromDataTable(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"TableInfo\":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        ///  
        /// 将对象转化为Json字符串 
        ///  
        /// 源对象 
        /// json数据 
        public static string ObjToJson(this object obj)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            return serialize.Serialize(obj);
        }

        ///  
        /// 将Json字符串转化为对象
        ///  
        /// Json字符串 
        /// 目标对象
        public static T JsonToObj(string strJson)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            return serialize.Deserialize(strJson);
        }

        ///  
        /// 将对象转化为Json字符串(控制深度 )
        ///  
        /// 源对象 
        /// 深度 
        /// json数据 
        public static string ObjToJson(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            serialize.RecursionLimit = recursionDepth;
            return serialize.Serialize(obj);
        }

        ///  
        /// 将Json字符串转化为对象(控制深度 )
        ///  
        /// Json字符串 
        /// 深度 
        /// 目标对象
        public static T JsonToObj(string strJson, int recursionDepth)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            serialize.RecursionLimit = recursionDepth;
            return serialize.Deserialize(strJson);
        }

        ///  
        /// 将DataTable转换为JSON字符串
        ///  
        /// DataTable 
        /// json数据 
        public static string DataTableToJson(DataTable dt)
        {
            Dictionary dic = new Dictionary();

            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary result = new Dictionary();

                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                dic.Add(index.ToString(), result);
                index++;
            }
            return ObjToJson(dic);
        }
    }


使用如下:


public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //反序列化成对象     
            String strJson = "{\"Name\":\"Test123\",\"Url\":\"http://www.126.com/\"}";
            Person p1 = JsonHelper.GetObjFromJson(strJson);
            Response.Write("
  • " + p1.Name + " " + p1.Url); Person p2 = JsonHelper.JsonToObj(strJson); Response.Write("
  • " + p2.Name + " " + p2.Url); } protected void Button2_Click(object sender, EventArgs e) { //对象的序列化 String JSONString = string.Empty; Person p1 = new Person(); p1.Name = "Test123'\"\n\r\t"; p1.Url = "http://www.126.com/"; JSONString = JsonHelper.GetJsonFromObj(p1); Response.Write("
  • " + JSONString); JSONString = JsonHelper.ObjToJson(p1); Response.Write("
  • " + JSONString); } } /// /// 类对象需要标记为DataContractAttribute /// [DataContractAttribute] class Person { //成员需要标记为 DataMember [DataMember] public string Name { set; get; } [DataMember] public string Url { set; get; } }

  • Json.NET json字符串反序列化为json对象 


    如何将一个字符串转换为JSON对象呢?如果先创建一个类的话,那就太累了。

    var o = new
    {
       a = 1,
       b = "Hello, World!",
       c = new[] { 1, 2, 3 },
       d = new Dictionary { { "x", 1 }, { "y", 2 } }
    };

    var json = JsonConvert.SerializeObject(o);

    现在json是一个字符串。

    第一种做法(匿名类):

    var anonymous = new { a = 0, b = String.Empty, c = new int[0], d = new Dictionary() };
    var o2 = JsonConvert.DeserializeAnonymousType(json, anonymous);

    Console.WriteLine(o2.b);
    Console.WriteLine(o2.c[1]);

    第二种做法(匿名类):

    var o3 = JsonConvert.DeserializeAnonymousType(json, new { c = new int[0], d = new Dictionary() });

    Console.WriteLine(o3.d["y"]);

    DeserializeAnonymousType 只是借助这个匿名对象参数(anonymous) 反射类型而已,也就是说它和反序列化结果并非同一个对象。正如 o3 那样,我们也可以只提取局部信息。

     

    第三种做法(索引器):

    实际上,我们也可以直接反序列化为 JObject,然后通过索引器直接访问。JObject、JProperty 等都继承自 JToken,它重载了基元类型转换操作符,我们可以直接得到实际结果。
    var o2 = JsonConvert.DeserializeObject(json) as JObject;

    Console.WriteLine((int)o2["a"]);
    Console.WriteLine((string)o2["b"]);
    Console.WriteLine(o2["c"].Values().Count());
    Console.WriteLine((int)o2["d"]["y"]);



    你可能感兴趣的:(ASP.NET)