Optimized JSON serializer / deserializer as an extension method?

I would like to serialize any object in JSON as simple as possible and then just convert it back to type = safe object. Can someone tell me what I am doing wrong in the FromJSONString extension method?

Edit

For your convenience, the following is a complete and functional extension method. 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;
        }
    }
+3
source share
2 answers

This does not work as expected in the case of inherited objects.

deserialization returns only the base object, not the serialized object. Changing the serialization as shown below will solve this problem.

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
source

JSON MemoryStream . , :

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

Source: https://habr.com/ru/post/1787229/


All Articles