Optimized JSON serialiser / deserialiser as an extension method?

最后都变了- 提交于 2019-12-31 02:12:05

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4771582/optimized-json-serialiser-deserialiser-as-an-extension-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!