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.

Comments

  1. So what are you trying to say at the end??. if not using dynamic or Json dictionary, Do you suggest any other way to convert Json to C# object ?.

    ReplyDelete

Post a Comment

Popular Posts