zoukankan      html  css  js  c++  java
  • [转]JSON序列化与反序列化

    使用微软自带的Json库

    方法一:引入System.Web.Script.Serialization命名空间使用 JavaScriptSerializer类实现简单的序列化

    序列化类:Personnel

            public class Personnel
            {
                public int Id { get; set; }
                public string Name { get; set; }
            }

    执行序列化反序列化:

            protected void Page_Load(object sender, EventArgs e)
            {
                Personnel personnel = new Personnel();
                personnel.Id = 1;
                personnel.Name = "小白";


                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                //执行序列化
                string r1 = jsonSerializer.Serialize(personnel);
                
                //执行反序列化
                Personnel _Personnel = jsonSerializer.Deserialize<Personnel>(r1);
             }
    复制代码
            protected void Page_Load(object sender, EventArgs e)
            {
                Personnel personnel = new Personnel();
                personnel.Id = 1;
                personnel.Name = "小白";


                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                //执行序列化
                string r1 = jsonSerializer.Serialize(personnel);
                
                //执行反序列化
                Personnel _Personnel = jsonSerializer.Deserialize<Personnel>(r1);
             }
    复制代码

    r1输出结果:{"Id":1,"Name":"小白"}

    可以使用 ScriptIgnore属性标记不序列化公共属性或公共字段。

            public class Personnel
            {
                [ScriptIgnore]
                public int Id { get; set; }
                public string Name { get; set; }
            }

    r1输出结果:{"Name":"小白"}

    方法二:引入 System.Runtime.Serialization.Json命名空间使用 DataContractJsonSerializer类实现序列化

    序列化类:People

            public class People
            {
                public int Id { get; set; }
                public string Name { get; set; }
            }

     执行序列化反序列化

            protected void Page_Load(object sender, EventArgs e)
            {
                People people = new People();
                people.Id = 1;
                people.Name = "小白";


                DataContractJsonSerializer json = new DataContractJsonSerializer(people.GetType());
                string szJson = "";
                //序列化
                using (MemoryStream stream = new MemoryStream())
                {
                    json.WriteObject(stream, people);
                    szJson = Encoding.UTF8.GetString(stream.ToArray());
                }
                //反序列化
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
                    People _people = (People)serializer.ReadObject(ms);
                }
             }

    szJson输出结果:{"Id":1,"Name":"小白"}

    可以使用IgnoreDataMember:指定该成员不是数据协定的一部分且没有进行序列化,DataMember:定义序列化属性参数,使用DataMember属性标记字段必须使用DataContract标记类 否则DataMember标记不起作用。

            [DataContract]
            public class People
            {
                [DataMember(Name = "id")]
                public int Id { get; set; }
                [IgnoreDataMember]
                public string Name { get; set; }
            }

    输出结果: {"id":1}

    附 :泛型json序列化类

    namespace Communication
    {
        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Linq;
        using System.Runtime.Serialization.Json;
        using System.Text;
    
        /// <summary>
        /// Serialize and deserialize JSON object.
        /// </summary>
        internal class JsonHelper
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="JsonHelper" /> class.
            /// </summary>
            public JsonHelper()
            {
            }
    
            /// <summary>
            /// serialize object to JSON object. 
            /// </summary>
            /// <typeparam name="T">the type of the serializing target.</typeparam>
            /// <param name="obj">the instance of the serializing target.</param>
            /// <returns>JSON string.</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>
            /// de-serialize object to JSON object. 
            /// </summary>
            /// <typeparam name="T">the type of the de-serializing target.</typeparam>
            /// <param name="szjson">the JSON string</param>
            /// <returns>the instance of the de-serializing target.</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);
                }
            }
        }
    }
    

      

    还可以使用Json.net进行Json序列化

    这里下载:http://www.newtonsoft.com/products/json/

  • 相关阅读:
    「LuoguP1627 / T36198」 [CQOI2009]中位数
    「LuoguT36048」 Storm in Lover
    「LuoguP3252」 [JLOI2012]树
    「LuoguP2170」 选学霸(01背包
    「LuoguP3191」 [HNOI2007]紧急疏散EVACUATE(最大流
    「网络流24题」「LuoguP2774」方格取数问题(最大流 最小割
    「LuoguP3381」【模板】最小费用最大流
    ACTIVEMQ主题、队列设置用户名密码
    activemq消息生产者与消息消费者简单例子
    ActiveMQ使用线程池实现消息的生产与消费
  • 原文地址:https://www.cnblogs.com/luohengstudy/p/4193151.html
Copyright © 2011-2022 走看看