Does .NET 4 have a built-in JSON serializer/deserializer?

江枫思渺然 提交于 2019-11-26 08:10:10

问题


Does .NET 4 come with any class that serializes/deserializes JSON data?

  • I know there are 3rd-party libraries, such as JSON.NET, but I am looking for something built right into .NET.

  • I found Data Contracts on MSDN, but it is for WCF, not for Winforms or WPF.


回答1:


You can use the DataContractJsonSerializer class anywhere you want, it is just a .net class and is not limited to WCF. More info on how to use it here and here.




回答2:


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.




回答3:


Use this generic class in order to serialize / deserialize JSON. You can easy serialize complex data structure like this:

Dictionary<string, Tuple<int, int[], bool, string>>

to JSON string and then to save it in application setting or else

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;
    }
}



回答4:


.NET4 has a built-in JSON Class,such as DataContractJsonSerializer ,but it is very weak,it doesn't support multidimentional array. I suggest you use JSON.Net



来源:https://stackoverflow.com/questions/3275863/does-net-4-have-a-built-in-json-serializer-deserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!