优化 JSON 序列化器/反序列化器作为扩展方法?

发布于 2024-10-14 05:47:14 字数 829 浏览 3 评论 0原文

我想尽可能轻松地将任何对象序列化为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兮子 2024-10-21 05:47:15

您必须向 MemoryStream 提供要解码的 JSON 字符串。具体来说,您必须更改:

   MemoryStream stream1 = new MemoryStream(); 

实际检索字符串字节:

   MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(obj))

也就是说,我还要确保进行适当的内存清理并处置我的对象...另外,而不是使用 StreamReader (也应该处置),只需将内存流重新编码为 UTF-8 字符串。请参阅下面的清理代码。

   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;
     }
   }
夕色琉璃 2024-10-21 05:47:15

对于继承的对象,这不能按预期工作。

反序列化仅返回基础对象,而不返回序列化对象。按如下方式更改序列化将解决此问题。

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());
            }
        }

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());
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文