Json序列化和反序列化其实是老掉牙的话题了,不过很多初学Windows8开发的朋友有的可能还不知道,我就在这里简单的提一下。
我曾经写过Windows Phone开发经验谈(5)-Json的序列化和反序列化其实这个控件同样适用于Windows8 ,但是今天主要说的是利用微软自带的DataContractJsonSerializer类进行序列化和反序列化。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BaiduTieba.Utility; using System.Runtime.Serialization.Json; using BaiduTieba.Extension; namespace BaiduTieba.Utility { public class JsonHelper<T> { public static T Convert(Stream stream) { try { return (T)(Deserialize(stream, typeof(T))); } catch (Exception exc) { throw exc; } } public static object Deserialize(Stream streamObject, Type serializedObjectType) { if ((serializedObjectType == null) || (streamObject == null)) { return null; } System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(serializedObjectType); return serializer.ReadObject(streamObject); } public static object Deserialize(string json, Type serializedObjectType) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(serializedObjectType); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { return serializer.ReadObject(ms); } } public static string Serialize(object objForSerialization) { string str = string.Empty; if (objForSerialization == null) { return str; } System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(objForSerialization.GetType()); using (MemoryStream stream = new MemoryStream()) { serializer.WriteObject(stream, objForSerialization); byte[] buffer = new byte[stream.Length]; stream.Position = 0L; stream.Read(buffer, 0, buffer.Length); return buffer.ToStringByUTF8Format(); } } public static void Serialize(Stream streamObject, object objForSerialization) { if ((objForSerialization != null) && (streamObject != null)) { new System.Runtime.Serialization.Json.DataContractJsonSerializer(objForSerialization.GetType()).WriteObject(streamObject, objForSerialization); } } } }
上面是我写好的一个帮助类JsonHelper封装了DataContractJsonSerializer。使用起来非常的简单。
JsonHelper<HotPicModel>.Convert(stream);
如上代码,就可以把Json转换成HotPicModel这个实体类了。
大家可以自己试试写写序列化的方法,这篇说的比较简单,欢迎大家留意讨论.