63

.NET 4 是否带有任何对 JSON 数据进行序列化/反序列化的类?

  • 我知道有 3rd-party 库,例如JSON.NET,但我正在寻找内置于 .NET 中的东西。

  • 我在 MSDN 上找到了Data Contracts,但它适用于 WCF,而不适用于 Winforms 或 WPF。

4

4 回答 4

41

您可以在任何地方使用DataContractJsonSerializer类,它只是一个 .net 类,不限于 WCF。有关如何在此处此处使用它的更多信息。

于 2010-07-18T14:27:52.493 回答
30

There's the JavaScriptSerializer class (although you will need to reference the System.Web.Extensions assembly the class works perfectly fine in WinForms/WPF applications). Also even if the DataContractJsonSerializer class was designed for WCF it works fine in client applications.

于 2010-07-18T14:25:10.527 回答
4

使用这个泛型类来序列化/反序列化 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;
    }
}
于 2017-11-24T00:51:24.270 回答
0

.NET4 有一个内置的 JSON 类,例如 DataContractJsonSerializer ,但它很弱,不支持多维数组。我建议你使用 JSON.Net

于 2018-11-01T11:50:25.930 回答