|<<>>|169 of 275 Show listMobile Mode

Generating JSON from Dart object graphs

Published by marco on

 A while back, I participated in an evaluation of languages that could replace JavaScript for our web front-end development language at Encodo. We took a look at two contenders: Dart and TypeScript. At the time, Dart was weaker for the following reasons:

  • It had not yet been released
  • It had little to no tool support
  • Integration with existing JS libraries was somewhat laborious

Though TypeScript has its weaknesses (it has technically not yet hit a 1.0 release), we eventually decided to go in that direction. The tool support in Visual Studio and ReSharper are both improving steadily and have gotten quite good. We’ve had quite positive results in one larger project.

Even with Dart in our wake, I am still curious to see how people are using it. I was surprised by the claims in the article Why Dart should learn JSON while it’s still young by Max Horstmann.

Since Dart is not directly compatible with JavaScript, as TypeScript is, neither can a given JSON-formatted string be implicitly interpreted. Instead, you can import it using a library function. This is not really a problem, though one wonders if there are performance penalties for Dart that are not present in JavaScript/TypeScript.

Where the problem arises is in exporting JSON, which does not happen automagically. In non–client-side languages like C#, NewtonSoft’s JSON.Net library can serialize pretty much anything using reflection. JSON isn’t baked into the language, but that isn’t too surprising. However, in Dart, positioned as a contender for taking over from JavaScript as the client-side language of choice, the solution recommended even by Dart language gurus is to implement toJson() on all objects that you want to export.

Either that, or use a probably non-optimized external library to serialize your object to JSON (likely using introspection, as JSON.Net does). I agree with the author of the blog that this is a red flag for using Dart in production projects. It’s strange that Dart doesn’t produce JSON without relying on external libraries. And the recommended library is, as of this writing, of pre-production/alpha quality—the version number is 0.1.0 and the TODO list includes a bullet point that exhorts the author to “Write tests!”.

So I’m still waiting to see what becomes of Dart, but the balkiness of the current solution for generating JSON not only makes it a bit of tough fit for many current web applications, but also makes us urge caution despite its having recently been released (1.0 came out in November 2013).