Monday, February 08, 2010

Json in .NET

I use Json all the time, but I feel like it’s super annoying in .NET.  Typically I’d call some web service that returns Json. In .NET it seems like the best thing to is to define a data contract and use the DataContractSerializer:

[DataContract]
public class Person
{
   [DataMember]
   public string FirstName { get; set; }

   [DataMember]
   public string LastName { get; set; }
}

then to deserialize whatever string of Json I got back. .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

public static Person DeserializeToPerson( string jsonString )
{
  using( MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes( jsonString ) ) )
  {
     DataContractJsonSerializer serializer =
        new DataContractJsonSerializer( typeof( Person ) );
     return ( Person )serializer.ReadObject( ms );
   }
}

Read more: clarity consulting

Posted via email from jasper22's posterous