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