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 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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With