Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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;
        }
    }
like image 830
makerofthings7 Avatar asked Jan 21 '23 16:01

makerofthings7


1 Answers

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;
     }
   }
like image 82
Chris Baxter Avatar answered Jan 30 '23 11:01

Chris Baxter