ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

ToJson

Json Conversion, uses DataContractJsonSerializer to deserialize item

Source

public static string ToJson<T>(this T item, System.Text.Encoding encoding = null, System.Runtime.Serialization.Json.DataContractJsonSerializer serializer=null)
{
  encoding = encoding ?? Encoding.Default;
  serializer = serializer ?? new DataContractJsonSerializer(typeof(T));

  using (var stream = new System.IO.MemoryStream())
  {
    serializer.WriteObject(stream, item);
    var json = encoding.GetString((stream.ToArray()));

    return json;
  }        
}

Example

[Authorize]
public ActionResult Process(MyLovelyModel model)
{
  processor.Process(model);
  Json(model.JsonDeserialize());
}

Author: Arek Bal

Submitted on: 30 okt 2012

Language: C#

Type: T

Views: 6754