Optimized JSON serialiser / deserialiser as an extension method?
I'd like to serialize any object as easily as possible to JSON, and then convert it back to the type=safe object simply. Can anyone tell me what I'm doing wrong in the "FromJSONString" extension method?
Edit
For your convenience, a complete and functional extension method is below. Do let me know if you see errors.
public static string ToJSONString(this object obj)
{
using (var stream = new MemoryStream())
{
var ser = new DataContractJsonSerializer(obj.GetType());
ser.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
public static T FromJSONString<T>(this stri开发者_运维知识库ng obj)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
T ret = (T)ser.ReadObject(stream);
return ret;
}
}
You have to provide the JSON string to the MemoryStream to be decoded. Specifically, you must change:
MemoryStream stream1 = new MemoryStream();
to actually retrieve the string bytes:
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(obj))
That being said, I would also make sure to do proper memory cleanup and dispose my objects... also, rather than using the StreamReader (which should also be disposed), simply re-encode the memory stream as a UTF-8 string. See below for cleaned up code.
public static String ToJSONString(this Object obj)
{
using (var stream = new MemoryStream())
{
var ser = new DataContractJsonSerializer(obj.GetType());
ser.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
public static T FromJSONString<T>(this string obj)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(obj)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
T ret = (T)ser.ReadObject(stream);
return ret;
}
}
This is not working as expected in case of inherited objects.
The deserialization returns only the base object and not the serialized object. Changing Serialization as below will solve this issue.
public static String ToJSONString(this Object obj)
{
using (var stream = new MemoryStream())
{
var ser = new DataContractJsonSerializer(typeof(object));
ser.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
精彩评论