zoukankan      html  css  js  c++  java
  • c#操作json的两种方式

    总结一下C#操作json的两种方式,都是将对象和json格式相转。

    1.JavaScriptSerializer,继承自System.Web.Script.Serialization

    private string Serializer<T>(T t)
            {
                JavaScriptSerializer json=new JavaScriptSerializer();
                return json.Serialize(t);
            }
    
    private T DeSerialze<T>(string strJeson) {
                JavaScriptSerializer strJeson1 = new JavaScriptSerializer();
               return strJeson1.Deserialize<T>(strJeson);
            }
    View Code

    2.DataContractJsonSerializer,继承自System.Runtime.Serialization.Json;

    代码如下
    /// <summary>
            /// create json data according to entity
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            /// <returns></returns>
            public  static  string GetJsonSerializar<T>(T t)
            {
                var ser = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream ms=new MemoryStream())
                {
                    ser.WriteObject(ms,t);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            /// <summary>
            /// parse json data accroding to json string data
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="jsonStr"></param>
            /// <returns></returns>
            public static T ParseFromJson<T>(string jsonStr)
            {
                //T obj = Activator.CreateInstance<T>();
                //using (MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
                //{
                //    DataContractJsonSerializer jsonSerializer=new DataContractJsonSerializer(obj.GetType());
                //    return (T) jsonSerializer.ReadObject(ms);
                //}
                var ser = new DataContractJsonSerializer(typeof(T));
                var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
                var obj = (T)ser.ReadObject(ms);
                return obj; 
            }
    View Code

    但是json在客户端和浏览器传递之间时,如果传递的是实体类的json格式数据,则这类实体类应该用协议去定义,例如:

    [DataContract]
        public class MsgEntity
        {
            [DataMember(Order = 0,IsRequired = true)]
            public string Msg { get; set; }
    
            [DataMember(Order = 1, IsRequired = false)]
            public string HtmlMsg { get; set; }
        }
    View Code
  • 相关阅读:
    2、编程语言与python简介
    1、计算机基础
    查询操作
    查看电脑秘钥方法
    C/C++掌握技能(三)
    Ubuntu 16.04虚拟机调整窗口大小自适应Windows 7
    Java正则表达式初学者使用法简介
    Java-String类型的参数传递问题
    Java中goto和break、continue实现区别
    C/C++掌握技能(三)
  • 原文地址:https://www.cnblogs.com/bradwarden/p/3255693.html
Copyright © 2011-2022 走看看