The Microsoft recommended JSON serializer is DataContractJsonSerializer
This class exists within the System.Runtime.Serialization assembly
The sample demonstrates deserializing from JSON data into an object.
MemoryStream stream1 = new MemoryStream();
Person p2 = (Person)ser.ReadObject(stream1);
To serialize an instance of the Person type to JSON, create the DataContractJsonSerializer first and use the WriteObject method to write JSON data to a stream.
Person p = new Person();
//Set up Person object...
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);
Update: Added Helper class
Here is a sample helper class that you can use for simple To/From Json serialization:
public static class JsonHelper
{
public static string ToJson<T>(T instance)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream())
{
serializer.WriteObject(tempStream, instance);
return Encoding.Default.GetString(tempStream.ToArray());
}
}
public static T FromJson<T>(string json)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
return (T)serializer.ReadObject(tempStream);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…