JSON 序列化與反序列化, 與XML相互轉換.

方式一: 使用於 JavaScriptSerializer類
適用於普通場景, Excel導入導出, 前臺傳輸查詢參數直接處理等.html

JavaScriptSerializer serializer = new 
       JavaScriptSerializer();
            serializer.MaxJsonLength = int.MaxValue;
            var qp = serializer.Deserialize<QueryP>(queryP);
        private class QueryP
        {
            public string OrgID { get; set; }
            public string KeyWords { get; set; }
        }



    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var gridHeaders = serializer.Deserialize<List<grid>>(GridHeaders);

     /// <summary>
    /// grid表頭
    /// </summary>
    [Serializable]
    public class grid
    {
        public string Text { get; set; }
        public string DataIndex { get; set; }
        public string Width { get; set; }
        public List<grid> Cols { get; set; }
        public bool Hiden { get; set; }
        public string xtype { get; set; }
        public string DataType { get; set; }//列類型
    }


方式二: (不推薦使用DataContractJsonSerializer) 功能較多, 僅放一個例子, 不深刻研究, 由於開源第三種方式不只功能多, 性能還強. 數據庫

//Person實體中的契約 [DataMember],[DataContract],是使用DataContractJsonSerializer序列化和反序列化必需要加的

//使用DataContractJsonSerializer方式須要引入的命名空間,在System.Runtime.Serialization.dll.中

 using System.Runtime.Serialization.Json;    

static void Main(string[] args)
    {
        //序列化操做
        Person p1 = new Person()
        {
            name = "fxhl",
            age = 23
        };
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Person));
        MemoryStream msObj = new MemoryStream();
        //將序列化以後的Json格式數據寫入流中
        js.WriteObject(msObj, p1);
        //從0這個位置開始讀取流中的數據
        msObj.Position = 0;     
        StreamReader sr = new StreamReader(msObj, Encoding.UTF8);
        string json = sr.ReadToEnd();
        Console.WriteLine(json);
        sr.Close();
        msObj.Close();
        //反序列化操做
        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(Person));
            Person model = (Person)deseralizer.ReadObject(ms);// //反序列化ReadObject
            Console.WriteLine(model.name);
        }
        Console.ReadKey();
    }
}
[DataContract]     
public class Person
{
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public int age { get; set; }
}

方式三: 引入 Newtonsoft.Json 使用. 

拓展方法使用, 能夠直接使用.  json

public static T DeserializeModel<T>(this T model, string json)
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception)
            {
                return model;
            }
        }

        public static T DeserializeModel<T>(this T model, DataTable dt)
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Newtonsoft.Json.JsonConvert.SerializeObject(dt));
            }
            catch (Exception)
            {
                return model;
            }
        }


        public static T DeserializeJSON<T>(this string json) where T : new()
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>((json));
            }
            catch (Exception)
            {
                return new T();
            }
        }


        public static string SerializeModel(this object model)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(model);
        }

        public static List<T> NMList<T>(this T model)// where T:new()
        {
            var L = new List<T>();
            return L;
        }

        public static Hashtable NMToHashTable<T>(this T model)
        {
            var ht = new Hashtable();
            foreach (var f in model.GetType().GetProperties())
            {
                ht[f.Name] = f.GetValue(model, new object[] { });
            }
            return ht;
        }

支持屬性轉譯 和忽略字段.
JsonIgnore 註解 和 PropertyName 註解等.ide

public class AuditModel
    {
        [JsonProperty(PropertyName = "checked", NullValueHandling = NullValueHandling.Ignore)]
        public string SuccessMsg { get; set; }

        [JsonIgnore]
        public HttpRequestBase context { get; set; }



最後, 利用Json.NET 完成Json到Xml 的轉換:(完成的xml傳輸到數據庫. 數據庫根據/root 取相應執行邏輯)性能

string JsonTOXml(string json, string modelName)
        {
            string _json = @"{
                              ""?xml"": {
                                ""@version"": ""1.0"",
                                ""@standalone"": ""no""
                              },
                              ""root"": {
                                ""modelName"": " + json + @"
                              }
                            }";
            _json = _json.Replace("modelName", modelName);
            return Newtonsoft.Json.JsonConvert.DeserializeXmlNode(_json).OuterXml;
        }


其餘優秀博客可參考:
https://www.cnblogs.com/fengxuehuanlin/p/5700282.html 
http://www.cnblogs.com/yunfeifei/p/4086014.html
https://blog.csdn.net/WuLex/article/details/83026080
http://www.cnblogs.com/wuhuacong/p/3698122.html

 this

相關文章
相關標籤/搜索