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

后端 未结 4 1506
遇见更好的自我
遇见更好的自我 2020-11-28 07:06

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 somethi

4条回答
  •  一生所求
    2020-11-28 07:43

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

    Dictionary>
    

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

    public class JsonSerializer
    {
        public string Serialize(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(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;
        }
    }
    

提交回复
热议问题