Serialize Your Objects to and from JSON

Here is some easy, generic code to serialize your objects to and from JSON:

Public Shared Function JsonEncode(ByVal input As Object) As String
  Dim serilizer = New DataContractJsonSerializer(input.GetType)
  Using ms = New MemoryStream()
    serilizer.WriteObject(ms, input)
    Return Encoding.Default.GetString(ms.ToArray())
  End Using
End Function
Public Shared Function JsonDecode(Of T)(ByVal input As String) As T
  Using ms = New MemoryStream(Encoding.Unicode.GetBytes(input))
    Dim serilizer = New DataContractJsonSerializer(GetType(T))
    Return DirectCast(serilizer.ReadObject(ms), T)
  End Using
End Function
public static string JsonEncode(object input)
{
var serilizer = new DataContractJsonSerializer(input.GetType());
  using (var ms = new MemoryStream())
{
serilizer.WriteObject(ms, input);
    return Encoding.Default.GetString(ms.ToArray());
}
}
public static T JsonDecode<T>(string input)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(input)))
{
var serilizer = new DataContractJsonSerializer(typeof(T));
    return (T)serilizer.ReadObject(ms);
}
}

Tip Submitted By: David McCarter

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s