Tuesday, June 24, 2014

JSON to C# POCO - again!

This is really frustrating.  There are so many (bad) ways to deserialize JSON in C#.

In my previous post, we discovered that dynamic types really are not a good way to do it.

Now I have discovered that new JavaScriptSerializer().Deserialize<T>(json) will not convert datetimes properly.  Json.Decode<T>(json) has the same issue.

EDIT:

Today I tried ReadAsAsync<T>.  I originally had datetime conversion issues, but it was because my C# POCO did not have the correct property names.  If the json is not from ASP.NET and the JSON keys have underscores, your POCO property names must have underscores also.

For reference:

2 SO Questions that are the most popular:
http://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object
http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object

2 Asp.NET articles that are helpful for ReadAsAsync
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

Monday, June 23, 2014

JSON to C# POCO - don't use dynamic types

Hi all,

Wow there are about a million questions and answers regarding this on stack overflow, "How do you convert JSON to a C# Object?".  There are a ton of different ways to do it.  One SO Q/A I looked at was this:


One of the answers suggests using a dynamic type, which sounds awesome.  Using a simple one liner, you can parse the JSON into an object.

dynamic user = Json.Decode(json);

Then you can do this.

var name = user.name;

GREAT!  But the problem is, the name field is not type checked at compile time.  For example, this will also compile.

var name = user.naem;  // Compiles but generates a run-time error!

This leads me to the conclusion that dynamic types are really no better than a dictionary.  For example, you could convert the JSON to a dictionary and have the same problem:

var name = user["name"]; // Compiles and runs!
var name = user["naem"]; // Compiles and has a run-time error.

I am going to NOT use dynamic types as much as possible.

Tuesday, June 10, 2014

CSS Page Transitions

Check out this cool page transition animation I made to slide pages in from the right and from the left.

SO Answer

Plunker