[英]Does .NET 4 have a built-in JSON serializer/deserializer?
您可以在任何地方使用DataContractJsonSerializer類,它只是一個.net類,並不僅限於WCF。 有關如何在此處和此處使用它的更多信息。
有JavaScriptSerializer類(雖然您需要引用System.Web.Extensions
程序集,但該類在WinForms / WPF應用程序中運行得非常好)。 即使DataContractJsonSerializer類是為WCF設計的,它也可以在客戶端應用程序中正常工作。
使用此泛型類來序列化/反序列化JSON。 您可以輕松地序列化復雜的數據結構,如下所示:
Dictionary<string, Tuple<int, int[], bool, string>>
到JSON字符串,然后將其保存在應用程序設置或其他
public class JsonSerializer
{
public string Serialize<T>(T aObject) where T : new()
{
T serializedObj = new T();
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
ser.WriteObject(ms, aObject);
byte[] json = ms.ToArray();
ms.Close();
return Encoding.UTF8.GetString(json, 0, json.Length);
}
public T Deserialize<T>(string aJSON) where T : new()
{
T deserializedObj = new T();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(aJSON));
DataContractJsonSerializer ser = new DataContractJsonSerializer(aJSON.GetType());
deserializedObj = (T)ser.ReadObject(ms);
ms.Close();
return deserializedObj;
}
}
.NET4有一個內置的JSON類,比如DataContractJsonSerializer,但它非常弱,它不支持多維數組。 我建議你使用JSON.Net
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.