优化 JSON 序列化器/反序列化器作为扩展方法?
我想尽可能轻松地将任何对象序列化为 JSON,然后简单地将其转换回 type=safe 对象。谁能告诉我“FromJSONString”扩展方法中我做错了什么?
编辑
为了您的方便,下面是一个完整且功能齐全的扩展方法。如果您发现错误,请告诉我。
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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须向 MemoryStream 提供要解码的 JSON 字符串。具体来说,您必须更改:
实际检索字符串字节:
也就是说,我还要确保进行适当的内存清理并处置我的对象...另外,而不是使用 StreamReader (也应该处置),只需将内存流重新编码为 UTF-8 字符串。请参阅下面的清理代码。
You have to provide the JSON string to the MemoryStream to be decoded. Specifically, you must change:
to actually retrieve the string bytes:
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.
对于继承的对象,这不能按预期工作。
反序列化仅返回基础对象,而不返回序列化对象。按如下方式更改序列化将解决此问题。
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.